在Android中升級SQLite版本可以通過以下步驟實現:
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 2;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Upgrade database
if (newVersion > oldVersion) {
// Add new table or alter existing table
db.execSQL("CREATE TABLE IF NOT EXISTS new_table (id INTEGER PRIMARY KEY, name TEXT)");
// Migrate data from old table to new table
db.execSQL("INSERT INTO new_table (id, name) SELECT id, name FROM old_table");
// Drop old table
db.execSQL("DROP TABLE IF EXISTS old_table");
}
}
}
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
注意:在升級數據庫時需要謹慎操作,尤其是在生產環境中。建議在升級數據庫之前備份數據庫以防數據丟失。