Android开发之Sqlite的使用

    在Android中存储数据可以用文件、数据库、网络,其中文件和数据库是最常用的,数据库我们常用的就是Sqlite,它是一种经量级的、嵌入式的关系型数据库;在android中当需要操作SQLite数据库的时候需要得到一个SQLiteOpenHelper对象,而SQLiteOpenHelper是一个抽象类,用户需要继承这个类

 

package com.example.sqlite.db;



import android.content.Context;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;



/**

 * DatabaseHelper作为一个访问SQLite的助手类,提供两个方面的功能,

 * 第一,getReadableDatabase(),getWritableDatabase()可以获得SQLiteDatabse对象,通过该对象可以对数据库进行操作

 * 第二,提供了onCreate()和onUpgrade()两个回调函数,允许我们在创建和升级数据库时,进行自己的操作

 * @author Administrator

 *

 */

public class DatabaseHelper extends SQLiteOpenHelper{



	public static final int VERSION = 1;

	public DatabaseHelper(Context context, String name, CursorFactory factory,

			int version) {

		super(context, name, factory, version);

		// TODO Auto-generated constructor stub

	}

	public DatabaseHelper(Context context, String name){

		this(context, name, VERSION);

		Log.i("debug", "DatabaseHelper");

	}

	public DatabaseHelper(Context context, String name, int version){

		this(context, name, null, version);

	}

	

	

	@Override

	public void onCreate(SQLiteDatabase db) {

		// TODO Auto-generated method stub

		Log.i("debug", "create a database");

		//执行SQL语句

		db.execSQL("create table user (id int, name varchar(20))");

	}

	@Override

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		// TODO Auto-generated method stub

		Log.i("debug", "Upgrade a database");

	}

}

下面是对数据库的进行增、删、改、查操作

 

布局文件

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent" >



    <Button

        android:id="@+id/create_db"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/create_db"/> 

    <Button

        android:id="@+id/update_db"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/update_db"/> 

    <Button

        android:id="@+id/insert"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/insert"/> 

    <Button 

        android:id="@+id/update"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/update"/>

    <Button 

        android:id="@+id/query"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/query"/>

    <Button 

        android:id="@+id/delete"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/delete"/>



</LinearLayout>


在Activity处理代码

 

 

package com.example.sqlite;



import com.example.sqlite.db.DatabaseHelper;

import android.os.Bundle;

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;



/**

 * SQLite的创建、更新、修改、插入、查询、删除操作

 * @author Administrator

 *

 */

public class SqliteActivity extends Activity {



	private Button create_db;

	private Button update_db;   //更新数据库的版本号

	private Button insert;

	private Button update;

	private Button query;

	private Button delete;

	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_sqlite);

		create_db = (Button)findViewById(R.id.create_db);

		update_db = (Button)findViewById(R.id.update_db);

		insert = (Button)findViewById(R.id.insert);

		update = (Button)findViewById(R.id.update);

		query = (Button)findViewById(R.id.query);

		delete = (Button)findViewById(R.id.delete);

		create_db.setOnClickListener(new CreateListener());

		update_db.setOnClickListener(new UpdateDBListener());

		insert.setOnClickListener(new InsertListener());

		update.setOnClickListener(new UpdateListener());

		query.setOnClickListener(new QueryListener());

		delete.setOnClickListener(new Deletelistener());

	}



	class CreateListener implements OnClickListener{



		@Override

		public void onClick(View arg0) {

			// TODO Auto-generated method stub

			Log.i("debug", "on create db");

			DatabaseHelper dbHelper = new DatabaseHelper(SqliteActivity.this, "text_mars_db");

			//只有调用了DatabaseHelper的getReadableDatabase()或getWritableDatabase()才会创建数据库

			SQLiteDatabase db = dbHelper.getWritableDatabase();

		}

		

	}

	/**

	 * 更新数据库的版本号

	 * @author Administrator

	 *

	 */

	class UpdateDBListener implements OnClickListener{



		@Override

		public void onClick(View arg0) {

			// TODO Auto-generated method stub

			Log.i("debug", "on update db");

			DatabaseHelper dbHelper = new DatabaseHelper(SqliteActivity.this, "text_mars_db", 2);

			SQLiteDatabase db = dbHelper.getReadableDatabase();

		}

		

	}

	

	class InsertListener implements OnClickListener{



		@Override

		public void onClick(View v) {

			// TODO Auto-generated method stub

			Log.i("debug", "insert db");

			ContentValues values = new ContentValues();

			//向该对象插入键值对,其中键是列名,值是希望插入这一列的值,值的数据类型必须一致

			values.put("id", 1);

			values.put("name", "zhang");

			DatabaseHelper dbHelper = new DatabaseHelper(SqliteActivity.this, "text_mars_db");

			SQLiteDatabase db = dbHelper.getWritableDatabase();

			//调用insert方法插入数据

			db.insert("user", null, values);

		}

		

	}

	class UpdateListener implements OnClickListener{



		@Override

		public void onClick(View v) {

			// TODO Auto-generated method stub

			Log.i("debug", "update db");

			DatabaseHelper dbHelper = new DatabaseHelper(SqliteActivity.this, "text_mars_db");

			SQLiteDatabase db = dbHelper.getWritableDatabase();

			ContentValues values = new ContentValues();

			values.put("name", "zhangsanfeng");

			//第一个参数是要更新的表名

			//第二个参数是一个ContentValeus对象

			//第三个参数是where子句

			db.update("user", values, "id=?", new String[]{"1"});	

		}

		

	}

	class QueryListener implements OnClickListener{



		@Override

		public void onClick(View v) {

			// TODO Auto-generated method stub

			Log.i("debug", "query db");

			DatabaseHelper dbHelper = new DatabaseHelper(SqliteActivity.this, "text_mars_db");

			SQLiteDatabase db = dbHelper.getReadableDatabase();

			Cursor cursor = db.query("user", new String[]{"id","name"}, "id=?", new String[]{"1"}, null, null, null);

			int count = cursor.getCount();

			System.out.println("query---count = >" + count);

			while(cursor.moveToNext()){

				String name = cursor.getString(cursor.getColumnIndex("name"));

				System.out.println("query--->" + name);

			}

		}

		

	}

	class Deletelistener implements OnClickListener{



		@Override

		public void onClick(View v) {

			// TODO Auto-generated method stub

			Log.i("debug", "delete db");

			DatabaseHelper dbHelper = new DatabaseHelper(SqliteActivity.this, "text_mars_db");

			SQLiteDatabase db = dbHelper.getWritableDatabase();

			db.delete("user", "id=?", new String[]{"1"});

		}

		

	}

	@Override

	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.

		getMenuInflater().inflate(R.menu.activity_sqlite, menu);

		return true;

	}



}

运行效果

 

样例代码

点击打开链接



你可能感兴趣的:(Android开发)