1.如果DB已經存在,onCreate
將不會調用。僅當您更改數據庫版本時,纔會調用onUpgrade
。 onUpgrade
如果您的APP數據庫發生了一些變化,您應該使用它,並且您必須順利地遷移新的數據結構。
public class DbInit extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "name";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE = "create table connections . .. . ...
public DbInit(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (isChangeFromToVersion(1, 2, oldVersion, newVersion)) {
//Execute UPDATE here
}
}
private boolean isChangeFromToVersion(int from, int to, int oldVersion, int newVersion) {
return (from == oldVersion && to == newVersion);
}
....
2.簡單的例子如何打開連接到數據庫並獲取光標對象。
公共類DAO {
private SQLiteDatabase database;
private DbInit dbHelper;
public ConnectionDAO(Context context) {
dbHelper = new DbInit(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public Connection getConnectionById(long id) {
Cursor cursor = null;
try {
open();
cursor = database.query(DbInit.TABLE_CONNECTIONS, allColumns, DbInit.COLUMN_ID + " = '" + id + "'", null, null, null, null);
if (!cursor.moveToFirst())
return null;
return cursorToConnection(cursor);
} finally {
if (cursor != null)
cursor.close();
close();
}
}
private Connection cursorToConnection(Cursor cursor) {
Connection connection = new Connection();
connection.setId(cursor.isNull(0) ? null : cursor.getInt(0));
connection.setName(cursor.isNull(1) ? null : cursor.getString(1));
.....
.....
return connection;
}
我已經看到,嘖嘖,但我有一個關於一個小問題。它說所有的表都必須有一個字段_id。但是我有一張不具備主鍵字段的表格。根據教程,我需要一個名爲_id的主鍵字段。現在,我不得不重新創建將丟失數據的表。該怎麼辦.. – divyang7
嗯...我用這個教程,並在我的ID列在一個表中作爲「ID」和我的其他表沒有一個主鍵整數,它適用於我... – TronicZomB
我編輯了我的問題,幷包括一個圖像也描述當前缺少主鍵_id的表的結構。休息所有的表都有一個主鍵_id,從而滿足您提供的教程條件。 – divyang7