简体   繁体   English

检查Android SQLite数据库中的特定列

[英]Check for specific column in Android SQLite database

I am trying to check if there is a specific column in my database when onUpgrade() gets called. 我试图在调用onUpgrade()时检查我的数据库中是否有特定的列。 Is there an easy way to check like 有没有一种简单的方法来检查

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

I saw some other answer, Pragma Table , but I don't know how to use it or even what it really is for. 我看到了其他一些答案, Pragma Table ,但我不知道如何使用它,甚至不知道它是什么。

Found a solution 找到了解决方案

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

Ok, before you run into bigger problems you should know that SQLite is limited on the ALTER TABLE command, it allows add and rename only no remove/drop which is done with recreation of the table. 好的,在你遇到更大的问题之前,你应该知道SQLite在ALTER TABLE命令上是有限的,它允许addrename不删除/删除,这是通过重新创建表来完成的。

You should always have the new table creation query at hand, and use that for upgrade and transfer any existing data. 您应始终拥有新的表创建查询,并将其用于升级和传输任何现有数据。 Note: that the onUpgrade methods runs one for your sqlite helper object and you need to handle all the tables in it. 注意:onUpgrade方法为您的sqlite帮助程序对象运行一个,您需要处理其中的所有表。

So what is recommended onUpgrade: 那么推荐使用什么升级:

  • beginTransaction 的BeginTransaction
  • run a table creation with if not exists (we are doing an upgrade, so the table might not exists yet, it will fail alter and drop) 运行一个表创建, if not exists (我们正在进行升级,因此表可能还不存在,它将失败更改和删除)
  • put in a list the existing columns List<String> columns = DBUtils.GetColumns(db, TableName); 列表中的现有列List<String> columns = DBUtils.GetColumns(db, TableName);
  • backup table ( ALTER table " + TableName + " RENAME TO 'temp_" + TableName ) 备份表( ALTER table " + TableName + " RENAME TO 'temp_" + TableName
  • create new table (the newest table creation schema) 创建新表(最新的表创建模式)
  • get the intersection with the new columns, this time columns taken from the upgraded table ( columns.retainAll(DBUtils.GetColumns(db, TableName)); ) 获取与新列的交集,这次是从升级的表中获取的columns.retainAll(DBUtils.GetColumns(db, TableName));
  • restore data ( String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName)); ) 恢复数据( String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName));
  • remove backup table ( DROP table 'temp_" + TableName ) 删除备份表( DROP table 'temp_" + TableName
  • setTransactionSuccessful setTransactionSuccessful

(This doesn't handle table downgrade, if you rename a column, you don't get the existing data transfered as the column names do not match). (这不会处理表降级,如果重命名列,则不会因列名不匹配而传输现有数据)。

.

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM