嗯,这是一个关于Android SQL Lite数据库的“最佳实践”的问题。Android数据库高级生命周期
我得到了我DBHandler
与所谓DBHelper
这样一个内部类创建一个SQLiteDatabase
:
private final DBHelper dbhelper;
SQLiteDatabase db = dbhelper.getReadableDatabase();
// Call the helper
private static class DBHelper extends SQLiteOpenHelper {
DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
// create Table01
String sql = "create table " + "... SQL stuff here";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("drop table if exists " + Table01);
onCreate(db);
}
}
另外,DBHandler
提供功能用于添加/检索数据到/从象例如表这个:
public void insertOrIgnore(String table, ContentValues values){
SQLiteDatabase db = this.dbhelper.getWritableDatabase();
try{
db.insertOrThrow(table, null, values);
}
catch (SQLException e){
e.printStackTrace();
Log.e(TAG, e.toString());
}
finally {
db.close();
}
}
public Cursor getTable1(){
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor cursor = db.query(Table1, null, null, null, null, null, TABEL_ID + " ASC");
return cursor;
}
当我需要从数据库中的数据我创建一个DBHandler对象并使用它的方法。
因此,在第一次应用程序运行时,我调用insertOrIgnore方法并添加我想稍后使用的数据。 每当我对数据库进行更改时,我需要卸载APP并重新安装,以使更改生效。这很糟糕,所以我想用DB_VERSION来处理那些东西。在更改数据库(模式或数据)之后,我将DB_VERSION ID更改为更高的数字。
所以我的问题是:
- 如果newDBversion> oldDBversion,SQLiteDatabase不到风度使用的onCreate不过的onUpdate。这工作正常,但只有模式更新 ,它会导致空白表。我想知道最佳实践,所以 之后onUpdate数据方法从DBHandler被再次调用。 请注意,DBHelper是内部类 DBHandler。
- 对于我的理解SQLiteDatabase onCreate方法是只有调用如果数据库不存在和onUpdate方法是 只有调用如果newDBversion> oldDBversion,是否正确?
- DBHandler必须是静态的还是单身?还是没有,因为类自己处理多个读/写?
我开朗了更好的解决方案,但是从我在网上和一些Android的书中发现,那种将数据添加到SQL数据库的就是它做的方式。但没有人解释如何更新数据(不是模式,每当dbversion发生变化时自动完成)
圣诞节后会看看它,感谢迄今和快乐hollidays! – masi 2011-12-24 12:43:25
好。因为第一个问题对我来说是最重要的,所以我仍然不能按照我想要的方式工作:-( 一些实现示例会很好,但是我找不到任何好的。 – masi 2011-12-30 00:50:27
我已经为第一个问题添加了提示。 – Yury 2011-12-30 07:17:22