【问题标题】:How to add a new column to Sqlite database table which does not exist in android?如何在 android 中不存在的 Sqlite 数据库表中添加新列?
【发布时间】:2013-10-10 04:45:44
【问题描述】:

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

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    我拼凑了几个cmets来得到这个:

    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;");
    }
    

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

    【讨论】:

    • 如果你的桌子上没有行怎么办?
    【解决方案2】:
    @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");
         }
        }
    }
    

    【讨论】:

    • 我们如何检查 onCreate() 或 onUpgrade() 本身是否存在列?什么是列存在???
    • 如果列不存在,则简单查询您的表cursor.getColumnIndex(String columnName) returns -1
    • ColunmExists 只是一个变量。
    • 您是否认为在 onCreate() 或 onUpgrade() 中为每次版本升级初始化并调用和使用它是一种很好的编程习惯。任何更好的解决方案都是可观的。
    • 这不会损害您的程序。这对于应用程序来说是正常的。如果newVersion&gt;oldVersion,你只需要初始化Cursor。所以不会每次都调用。查看修改。
    【解决方案3】:

    我使用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"
            )
        }
    }
    

    Ref link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多