下面這個很好的例子http://code.google.com/p/openintents/source/browse/trunk/notepad/NotePad/src/org/openintents/notepad/NotePadProvider.java?r=3878如何使用onUpgrade方法在Android中的SQLite表中修改類型?
我實現了我的sqlite數據庫升級系統。但是在上面的鏈接中,唯一的例子顯示瞭如何在表中添加新列。在onUpgrade方法的代碼段是
try {
db.execSQL("ALTER TABLE " + NOTES_TABLE_NAME + " ADD COLUMN "
+ Notes.TAGS + " TEXT;");
db.execSQL("ALTER TABLE " + NOTES_TABLE_NAME + " ADD COLUMN "
+ Notes.ENCRYPTED + " INTEGER;");
db.execSQL("ALTER TABLE " + NOTES_TABLE_NAME + " ADD COLUMN "
+ Notes.THEME + " TEXT;");
} catch (SQLException e) {
Log.e(TAG, "Error executing SQL: ", e);
// If the error is "duplicate column name" then everything is fine,
// as this happens after upgrading 2->3, then downgrading 3->2,
// and then upgrading again 2->3.
}
// *** other upgrade from version x->y
// ***
和的onCreate,是這樣的:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + NOTES_TABLE_NAME + " ("
// Version 2:
+ Notes._ID + " INTEGER PRIMARY KEY,"
+ Notes.TITLE + " TEXT,"
+ Notes.NOTE + " TEXT,"
+ Notes.CREATED_DATE + " INTEGER,"
+ Notes.MODIFIED_DATE + " INTEGER,"
// Version 3:
+ Notes.TAGS + " TEXT,"
+ Notes.ENCRYPTED + " INTEGER,"
+ Notes.THEME + " TEXT,"
// Version 4:
+ Notes.SELECTION_START + " INTEGER,"
+ Notes.SELECTION_END + " INTEGER,"
+ Notes.SCROLL_POSITION + " REAL"
+ ");");
}
現在我想沒有添加列一個新的數據庫版本,但我想只是改變類型在一個表中的某個字段。我怎樣才能做到這一點?
這裏http://sqlite.org/lang_altertable.html據說不可能改變字段類型。我怎樣才能繞過這個問題?
我在數據庫中以這種方式插入數據:
ContentValues v = new ContentValues();
v.put("field1", myString); // fileld1 in db is defined as integer
dbManager.updateTable("mytable", v, whereClause);
我怎樣才能使在這種情況下強制轉換?
我正在使用ContentValues在數據庫的整數字段中插入字符串數據。 (我編輯了我的答案)。在這種情況下我怎麼能做一個CAST? – GVillani82