首页 > 解决方案 > 更改表并添加列,但检查该列是否已存在于 android studio

问题描述

我正在尝试升级数据库。所以下面的方法被调用。

有5张桌子。我只想更改最后一个表。但是当 onupgrade 被调用时,最后一个表还没有创建并且不能在 Onupgrade 方法上改变它。

 @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {

创建表后。我想检查该列是否存在,如果不存在则更改表。我尝试了下面的代码,但它不起作用

 public static void createuserTable(SQLiteDatabase db, String tableName) {

    final String table = "CREATE TABLE IF NOT EXISTS "
                    + tableName + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT, addressTEXT, phone TEXT, phone2 TEXT)";

     Cursor cursor = db.rawQuery(table , null); // grab cursor for all data
            int deleteStateColumnIndex = cursor.getColumnIndex("email");  // see if the column is there
            if (deleteStateColumnIndex < 0) {
                // missing_column not there - add it
                Log.d("value dont exist","value dont exist");
            }
        db.execSQL(table);

      }

标签: androidandroid-sqlite

解决方案


理论上,您应该通过遵循定义的升级机制来知道该列是否存在。

但是,如果该列很容易唯一识别,那么您可以使用:-

public void createuserTable (SQLiteDatabase db, String tableName) {

    //Force table to exist (if it doesn't then why not include the email column in the definition? (rhetorical))
    final String table = "CREATE TABLE IF NOT EXISTS "
            + tableName + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT, addressTEXT, phone TEXT, phone2 TEXT)";

    String columnName = "email"; //<<<<<<<<<< change as appropriate
    String columnDefinition = " TEXT UNIQUE "; //<<<<<<<<<< change as appropriate
    Cursor cursor;
    if (((
            cursor = db.query(
                    "sqlite_master",
                    new String[]{
                            "sql"
                    },
                    "sql LIKE ? AND type = 'table' AND name = ?", 
                    new String[]{
                            "%" + columnName + "%",
                            tableName
                    }, 
                    null,
                    null,
                    null
                            )).getCount() < 0)){ 
        db.execSQL("ALTER TABLE " + tableName +" ADD COLUMN " + columnName + columnDefinition);
    }
    cursor.close();
}
  • 当然,列名不得与包含新列名的另一个列名冲突。

    • 例如,如果新的列名是 col1 并说一个列存在名称 thisiscol1,那么由于 col1 将被发现是 col1 的一部分,则不会执行 ALTER 命令。
  • 以上是原则性代码,尚未测试或运行,因此可能包含一些错误。


推荐阅读