4

在版本升级时,我想在 android 中不存在的 sqlite 数据库表中添加一个新列。如果该列已经存在,则不应更改该表。在 onUpgrade() 方法中,我不会删除表,因为我不想丢失数据。

4

3 回答 3

4

我拼凑了一些评论来得到这个:

Cursor cursor = database.rawQuery("SELECT * FROM MY_TABLE", null); // grab cursor for all data
int deleteStateColumnIndex = cursor.getColumnIndex("MISSING_COLUMN");  // see if the column is there
if (deleteStateColumnIndex < 0) { 
    // missing_column not there - add it
    database.execSQL("ALTER TABLE MY_TABLE ADD COLUMN MISSING_COLUMN int null;");
}

这故意忽略了数据库版本号,如果该列不存在,则纯粹添加该列(在我的情况下,版本号对我没有帮助,因为在应该添加此列时编号变得不稳定)

于 2014-07-18T09:51:22.360 回答
3
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    // If you need to add a column
    if (newVersion > oldVersion) {

     if(!ColunmExists) {
        db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
     }
    }
}
于 2013-10-10T05:06:21.263 回答
0

我曾经pragma找出列是否存在。

fun SupportSQLiteDatabase.safeRunQueryToAddColumn(
tableName: String,
columnName: String,
block: () -> Any) {
    
    val cursor = query(
        "SELECT count(*) FROM pragma_table_info('$tableName') WHERE name='$columnName'", null)

    val columnExisted = if (cursor.moveToNext()) {
        cursor.getInt(0) == 1 // row found
    } else false

    cursor.close()


    if (!columnExisted) {
        block()
    } else {
        Log.w(
            "ERROR",
            "column add ignored, table : $tableName : column $columnName already existed"
        )
    }
}

参考链接

于 2021-10-05T06:45:39.730 回答