简述:一个帮助类,帮助创建数据库和数据库版本管理。
使用必须创建一个子类来实现其onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int)方法,同时任意实现onOpen(SQLiteDatabase)方法,同时打开数据库操作必须保证数据库存在,如果不存在则创建它,并且对其必要的升级,维护其保持一个最佳的状态。使用本类提供内容开始创建数据库是非常容易的,首先必须对数据库进行升级,以避免在数据库启动后长期使用而阻塞数据。
其中:
onCreate(SQLiteDatabase db) : 当数据库被首次创建时执行该方法,一般将创建表等初始化操作在该方法中执行。
onUpgrade(SQLiteDatabse dv, int oldVersion,int new Version):当打开数据库时传入的版本号与当前的版本号不同时会调用该方法。
除了上述两个必须要实现的方法外,还可以选择性地实现onOpen 方法,该方法会在每次打开数据库时被调用。
SQLiteOpenHelper 类的基本用法是:当需要创建或打开一个数据库并获得数据库对象时,首先根据指定的文件名创建一个辅助对象,然后调用该对象的getWritableDatabase 或 getReadableDatabase方法 获得SQLiteDatabase 对象。
调用getReadableDatabase 方法返回的并不总是只读数据库对象,一般来说该方法和getWriteableDatabase 方法的返回情况相同,只有在数据库仅开放只读权限或磁盘已满时才会返回一个只读的数据库对象。
一、DBAdapter辅助类,创建、打开、关闭和使用一个SQLite数据库。
本例子是创建一个名为MyDB的数据库,包含一个名为contacts的表。这个表有3列:_id、name和email
package com.example.common;
import com.example.model.Contacts;
import android.R.string;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.ParcelUuid;
import android.util.Log;
public class DBAdapter {
final Context context;
DatabaseHelper dBHelper;
SQLiteDatabase db;
private static final String DATABASE_CREATE = "create table if not exists contacts(_id integer primary key autoincrement, "
+ "name text not null,email text not null);";
public DBAdapter(Context ctx) {
this.context = ctx;
dBHelper = new DatabaseHelper(context);
}
public static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, Contacts.DATABASE_NAME, null,
Contacts.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(Contacts.TAG, "Upgrading database from version " + oldVersion
+ "to " + newVersion + " , which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
public DBAdapter open() throws SQLException {
db = dBHelper.getWritableDatabase();
return this;
}
public void close() {
dBHelper.close();
}
public long insertContact(String name, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(Contacts.KEY_NAME, name);
initialValues.put(Contacts.KEY_EMAIL, email);
return db.insert(Contacts.DATABASE_TABLE, null, initialValues);
}
public boolean deleteContact(long rowId) {
return db.delete(Contacts.DATABASE_TABLE, Contacts.KEY_ROWID + "="
+ rowId, null) > 0;
}
public Cursor getAllContacts() {
// return db.query(Contacts.DATABASE_TABLE, new String[] {
// Contacts.KEY_ROWID, Contacts.KEY_NAME, Contacts.KEY_EMAIL },
// null, null, null, null, null);
// return db.rawQuery("select * from "+Contacts.DATABASE_TABLE, null);
// String sql = "select [Value] from AppConfig where KeyName =?";
// Cursor cursor = mDb.rawQuery(sql,new String[]{key});
// if (cursor.moveToFirst()) {
// result=cursor.getString(0);
// }
String sql = "select name from " + Contacts.DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
String string = cursor.getString(0);
}
return db.query(Contacts.DATABASE_TABLE, new String[] {
Contacts.KEY_ROWID, Contacts.KEY_NAME, Contacts.KEY_EMAIL },
null, null, null, null, null);
}
public Cursor getContact(long rowId) throws SQLException {
Cursor mCursor = db.query(true, Contacts.DATABASE_TABLE, new String[] {
Contacts.KEY_ROWID, Contacts.KEY_NAME, Contacts.KEY_EMAIL },
Contacts.KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateContact(long rowId, String name, String email) {
ContentValues args = new ContentValues();
args.put(Contacts.KEY_NAME, name);
args.put(Contacts.KEY_EMAIL, email);
return db.update(Contacts.DATABASE_TABLE, args, Contacts.KEY_ROWID
+ "=" + rowId, null) > 0;
}
}
Model类,存放静态变量。
package com.example.model;
public class Contacts {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String TAG = "DBAdapter";
public static final String DATABASE_NAME = "MyDB.db";
public static final String DATABASE_TABLE = "contacts";
public static int DATABASE_VERSION = 1;
}
活动调用:
public void btnInsert_onclick(View view) {
count++;
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertContact("浩" + count, "2xx672484xx@qq.com" + count);
id = db.insertContact("钱" + count, "qian@qq.com" + count);
db.close();
}
public void btnQuery_onclick(View view) {
DBAdapter db = new DBAdapter(this);
db.open();
Cursor cursor = db.getAllContacts();
if (cursor.moveToFirst()) {
do {
DialogHelper.showShortToast(this, "id:" + cursor.getString(0)
+ "\n" + "Name:" + cursor.getString(1) + "\n"
+ "Email:" + cursor.getString(2));
} while (cursor.moveToNext());
}
}
布局XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".DBAdapter"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="例子" />
<Button
android:id="@+id/btnInsert"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="btnInsert_onclick"
android:text="插入两行数据" >
</Button>
<Button
android:id="@+id/btnQuery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="btnQuery_onclick"
android:text="查询检索数据" />
</LinearLayout>
二、创建数据库、插入数据、更新 、查询等等,我们将查询后获取到的数据显示到TextView上。
运行效果
MySQLiteHelper
package xiaohang.zhimeng;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class MySQLiteHelper extends SQLiteOpenHelper{
//调用父类构造器
public MySQLiteHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
/**
* 当数据库首次创建时执行该方法,一般将创建表等初始化操作放在该方法中执行.
* 重写onCreate方法,调用execSQL方法创建表
* */
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists hero_info("
+ "id integer primary key,"
+ "name varchar,"
+ "level integer)");
}
//当打开数据库时传入的版本号与当前的版本号不同时会调用该方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Activity01
package xiaohang.zhimeng;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;
public class Activity01 extends Activity {
MySQLiteHelper myHelper;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
//创建MySQLiteOpenHelper辅助类对象
myHelper = new MySQLiteHelper(this, "my.db", null, 1);
//向数据库中插入和更新数据
insertAndUpdateData(myHelper);
//查询数据
String result = queryData(myHelper);
tv.setTextColor(Color.RED);
tv.setTextSize(20.0f);
tv.setText("名字\t等级\n"+result);
}
//向数据库中插入和更新数据
public void insertAndUpdateData(MySQLiteHelper myHelper){
//获取数据库对象
SQLiteDatabase db = myHelper.getWritableDatabase();
//使用execSQL方法向表中插入数据
db.execSQL("insert into hero_info(name,level) values('bb',0)");
//使用insert方法向表中插入数据
ContentValues values = new ContentValues();
values.put("name", "xh");
values.put("level", 5);
//调用方法插入数据
db.insert("hero_info", "id", values);
//使用update方法更新表中的数据
//清空ContentValues对象
values.clear();
values.put("name", "xh");
values.put("level", 10);
//更新xh的level 为10
db.update("hero_info", values, "level = 5", null);
//关闭SQLiteDatabase对象
db.close();
}
//从数据库中查询数据
public String queryData(MySQLiteHelper myHelper){
String result = "";
//获得数据库对象
SQLiteDatabase db = myHelper.getReadableDatabase();
//查询表中的数据
Cursor cursor = db.query("hero_info", null, null, null, null, null, "id asc");
//获取name列的索引
int nameIndex = cursor.getColumnIndex("name");
//获取level列的索引
int levelIndex = cursor.getColumnIndex("level");
for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {
result = result + cursor.getString(nameIndex)+ "\t\t";
result = result + cursor.getInt(levelIndex)+" \n";
}
cursor.close();//关闭结果集
db.close();//关闭数据库对象
return result;
}
@Override
protected void onDestroy() {
SQLiteDatabase db = myHelper.getWritableDatabase();//获取数据库对象
//删除hero_info表中所有的数据 传入1 表示删除所有行------>点击back按钮
db.delete("hero_info", "1", null);
super.onDestroy();
}
}