Check if a column exists in SQLite

前端 未结 15 519
我寻月下人不归
我寻月下人不归 2020-12-08 07:02

I need to check to see if a column exists and if it doesn\'t exist add it. From my research it looks like sqlite doesn\'t support IF statements and case statement should be

15条回答
  •  孤城傲影
    2020-12-08 07:11

    Some of these examples didn't worked for me. I'm trying to check whether my table already contains a column or not.

    I'm using this snippet:

    public boolean tableHasColumn(SQLiteDatabase db, String tableName, String columnName) {
        boolean isExist = false;
        Cursor cursor = db.rawQuery("PRAGMA table_info("+tableName+")",null);
        int cursorCount = cursor.getCount();
        for (int i = 1; i < cursorCount; i++ ) {
            cursor.moveToPosition(i);
            String storedSqlColumnName = cursor.getString(cursor.getColumnIndex("name"));
            if (columnName.equals(storedSqlColumnName)) {
                isExist = true;
            }
        }
        return isExist;
    }
    

    The examples above are querying the pragma table which is a metadata table and not the actual data, each column indicates the names, type and some other stuff about the table's columns. So the actual column names are within the rows.

    Hope that this helps someone else.

提交回复
热议问题