ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

前端 未结 14 1896
青春惊慌失措
青春惊慌失措 2020-11-28 08:45

We\'ve recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has alre

14条回答
  •  被撕碎了的回忆
    2020-11-28 09:34

    threre is a method of PRAGMA is table_info(table_name), it returns all the information of table.

    Here is implementation how to use it for check column exists or not,

        public boolean isColumnExists (String table, String column) {
             boolean isExists = false
             Cursor cursor;
             try {           
                cursor = db.rawQuery("PRAGMA table_info("+ table +")", null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        if (column.equalsIgnoreCase(name)) {
                            isExists = true;
                            break;
                        }
                    }
                }
    
             } finally {
                if (cursor != null && !cursor.isClose()) 
                   cursor.close();
             }
             return isExists;
        }
    

    You can also use this query without using loop,

    cursor = db.rawQuery("PRAGMA table_info("+ table +") where name = " + column, null);
    

提交回复
热议问题