Android 有關SQLite的使用以及資料庫版本的升級
SQLite是在安卓中經常用到的資料存放區方式,一般用來儲存在本地的臨時資料。應用版本升級的時候,資料庫版本也要跟著升級。
public class DBHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
String sql = create table if not exists my_product+(id integer primary key, category varchar, biaoqian varchar, +
bgState integer, bqState Integer);
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public DBHelper(Context context, String name, CursorFactory factory,
int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVision, int newVision) {
Log.i(Allen, 執行資料庫升級);
// TODO Auto-generated method stub
db.delete(my_product,null,null);
db.execSQL(sql);
}
}
上面的代碼是一個簡單的sqlite的使用,databaseHelper得繼承類SQLiteOpenHelper,一般至少要實現兩個方法,一個是onCreate方法,在建立databaseHelper對象的時候調用。上面的sql語句是穿件一個資料庫表。另一個要實現的方法是onUpgrade方法,該方法在版本號碼改變的時候調用。上面的意思是刪除原來的資料庫表,重新建立一個表。
在Activity中使用的時候,
private static String DATABASE_NAME = shipin.db;
private static String TABLE_NAME = my_product;
DBHelper dbHelper = new DBHelper(this,DATABASE_NAME,null,2);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] {
biaoqian,bgState,bqState}, category = ?, new String[] {cap}, null, null, null);
// 將游標移動到下一行,從而判斷該結果集是否還有下一條資料,如果有則返回true,沒有則返回false
while (cursor.moveToNext()) {
biaoqian = cursor.getString(cursor.getColumnIndex(biaoqian));//標籤文字
bgState = cursor.getInt(cursor.getColumnIndex(bgState)); //背景狀態,是否使用過
bqState = cursor.getInt(cursor.getColumnIndex(bqState));//標籤狀態,用來區分標籤背景顏色
list_biaoqian.add(biaoqian);
listImageState.add(bgState);
listBg.add(bqState);
}
以上是從資料庫中查詢資料的方法,把符合要求的資料添加到list中。
Cursor cursor = db.query(TABLE_NAME, new String[] {
biaoqian,bgState,bqState}, category = ?, new String[] {cap}, null, null, null);
這一句是具體的查詢語句,TABLE_NAME是資料庫表名,new String[]是要查詢的那幾列,category=?是查詢條件,相當於where,後面的new String[]是具體的查詢條件,該語句查詢的是category=cap的biaoqian、bgState、bqState的值。
DBHelper dbHelper = new DBHelper(this,DATABASE_NAME,null,2);這一句中的參數2,
就是資料庫版本號碼,建立資料庫表的時候預設資料看版本是1,該出的參數為2,版本升級,
此時就會執行onUpgrade方法。要注意的一點是,資料庫的版本號碼只能升或者不變,不能降。
否則會報錯。
ps:工作中就是因為應用版本升級了,資料庫版本沒有升級,而表結構改變了,
導致升級後的應用不能用。