Android 相干SQLite的使用以及数据库版本的升级

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:工作中就是因为应用版本升级了,数据库版本没有升级,而表结构改变了,

导致升级后的应用不能用。

版权声明:本文为博主原创文章,未经博主允许不得转载。