Check if a column exists in SQLite

前端 未结 15 502
我寻月下人不归
我寻月下人不归 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:29

    I updated the function of a friend... tested and working now

        public boolean isFieldExist(String tableName, String fieldName)
    {
        boolean isExist = false;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
    
    
        if (res.moveToFirst()) {
            do {
                int value = res.getColumnIndex("name");
                if(value != -1 && res.getString(value).equals(fieldName))
                {
                    isExist = true;
                }
                // Add book to books
    
            } while (res.moveToNext());
        }
    
        return isExist;
    }
    

提交回复
热议问题