我有一个数据库,我想添加一个列,我更改了静态数据库版本但是当我在我的设备上运行程序时,新列仍然没有,所以我猜我的onUpdate没有被调用,我不确定为什么.
这就是我创建数据库的方式
private static class DatabaseHelper extends sqliteOpenHelper { DatabaseHelper(Context context) { super(context,DATABASE_NAME,null,DATABASE_VERSION); } @Override public void onCreate(sqliteDatabase db) { createTables(db); } @Override public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { Log.w("CalendarDB","Upgrading database from version " + oldVersion + " to " + newVersion + ",which will destroy all old data"); db.execsql("DROP TABLE IF EXISTS Events_Table"); onCreate(db); } private void createTables(sqliteDatabase db){ db.execsql("CREATE TABLE " + EVENTS_TABLE + "(" + ID + " integer primary key autoincrement," + EVENT + " TEXT," + LOCATION + " TEXT," + DESCRIPTION + " TEXT," + DATE + " TEXT," + START + " LONG," + END + " TEXT," + REAL_START_TIME + " TEXT," + REAL_END_TIME + " TEXT," + COLOR + " TEXT," + BLINK + " TEXT," + VIBRATE + " TEXT," + RING_TONE_PATH + " TEXT," + ICON + " TEXT," + REMINDERS + " TEXT," + START_WITH_REMINDER + " TEXT," + CALENDAR_ID + " TEXT," + EVENT_ID + " TEXT);"); } }
还有什么我需要做的才能让onUpdate被调用吗?我试过跟随this answer,但仍然没有结果
解决方法
为了在Android中升级数据库,您应该将DATABASE_VERSION增加1,以便sqlOpenHelper知道它必须调用onUpgrade方法.
Rembember
这仅在您调用getWritableDatabase()时有效,否则将无法升级.如果更改版本并调用getReadableDatabase,它将显示异常
throw new sqliteException("Can't upgrade read-only database from version " + db.getVersion() + " to " + mNewVersion + ": " + path);
但为什么?
你看到当你拨打getWritableDatabase代码检查时,版本是相同的:
if (version != mNewVersion) { db.beginTransaction(); try { if (version == 0) { onCreate(db); } else { if (version > mNewVersion) { onDowngrade(db,version,mNewVersion); } else { onUpgrade(db,mNewVersion); } } db.setVersion(mNewVersion); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }
更新
事实证明它应该与getReadableDatabase()一起使用,因为在代码中你总是得到一个WrittableDatabase.所以它应该适用于这两种方法,这里是getReadableDatabase()的文档:
Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem,such as a full disk,requires the database to be opened read-only. In that case,a read-only database object will be returned. If the problem is fixed,a future call to getWritableDatabase() may succeed,in which case the read-only database object will be closed and the read/write object will be returned in the future.