Check specific column in Android SQLite database

I am trying to check if there is a specific column in my database when calling onUpgrade (). Is there an easy way to check how

if(database does not have specific column){
db.execSQL("ALTER TABLE table" + " ADD COLUMN column" );
}

I saw some other Pragma Table answer , but I don’t know how to use it or even for what it really is intended for.

+3
source share
2 answers

Well, before you encounter major problems, you should know that SQLite limited ALTER TABLE command, it allows add, and renameremove only the removal / deletion is performed with the re-creation of the table.

. : onUpgrade sqlite, .

, Upgrade:

  • BeginTransaction
  • if not exists ( , , )
  • List<String> columns = DBUtils.GetColumns(db, TableName);
  • (ALTER table " + TableName + " RENAME TO 'temp_" + TableName)
  • ( )
  • , , (columns.retainAll(DBUtils.GetColumns(db, TableName));)
  • (String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName)); )
  • (DROP table 'temp_" + TableName)
  • setTransactionSuccessful

( , , , , ).

.

public static List<String> GetColumns(SQLiteDatabase db, String tableName) {
    List<String> ar = null;
    Cursor c = null;
    try {
        c = db.rawQuery("select * from " + tableName + " limit 1", null);
        if (c != null) {
            ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
        }
    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (c != null)
            c.close();
    }
    return ar;
}

public static String join(List<String> list, String delim) {
    StringBuilder buf = new StringBuilder();
    int num = list.size();
    for (int i = 0; i < num; i++) {
        if (i != 0)
            buf.append(delim);
        buf.append((String) list.get(i));
    }
    return buf.toString();
}
+6

    try {
            db.execSQL("ALTER TABLE notes" + " ADD COLUMN Week");
        } catch (SQLException e) {
            Log.i("ADD COLUMN Week", "Week already exists");
        }
+21

Source: https://habr.com/ru/post/1760779/


All Articles