简体   繁体   English

将字段添加到现有sqlite数据库

[英]Adding a field to an existing sqlite database

I have an existing app published and I want to add location coords field to the sqlite database. 我已经发布了现有应用程序,我想将位置coords字段添加到sqlite数据库。

I want to know if it is possible to do this without creating a new table in the database. 我想知道是否可以在不在数据库中创建新表的情况下执行此操作。 I don't want to overwrite the users existing database entries, I just want to add this new field for existing database entries and give it a default value. 我不想覆盖用户现有的数据库条目,我只想为现有的数据库条目添加这个新字段并给它一个默认值。

Is this possible? 这可能吗?

Yes it is, 是的,

You need to write your onUpgrade() method when you update your table. 更新表时需要编写onUpgrade()方法。 Currently, I use the following to create a new table with the new column and to copy all my current data over. 目前,我使用以下内容创建一个包含新列的新表,并复制我当前的所有数据。 Hopefully you can adapt this to your code. 希望您可以根据您的代码进行调整。

@Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);

            db.beginTransaction();
            try {
                db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_UPGRADE);
                List<String> columns = GetColumns(db, DATABASE_TABLE);
                db.execSQL("ALTER table " + DATABASE_TABLE + " RENAME TO 'temp_" + DATABASE_TABLE + "'");
                db.execSQL("create table " + DATABASE_UPGRADE);
                columns.retainAll(GetColumns(db, DATABASE_TABLE));
                String cols = join(columns, ","); 
                db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", DATABASE_TABLE, cols, cols, DATABASE_TABLE));
                db.execSQL("DROP table 'temp_" + DATABASE_TABLE + "'");
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }
    }

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

This contains onUpgrade() and two helper methods. 它包含onUpgrade()和两个辅助方法。 DATABASE_UPGRADE is a string that contains the upgrade database: DATABASE_UPGRADE是一个包含升级数据库的字符串:

private static final String DATABASE_UPGRADE =
    "notes (_id integer primary key autoincrement, "
    + "title text not null, "
    + "body text not null, "
    + "date text not null, "
    + "edit text not null, "
    + "reminder text, "
    + "img_source text, "
    + "deletion, "
    + "priority)";

Quick note about how this works: 快速说明这是如何工作的:

  1. Check if current version of the table already exists (it never should) as onUpgrade() shouldn't get called in this case. 检查表的当前版本是否已经存在(它永远不应该),因为在这种情况下不应该调用onUpgrade()
  2. Since that failed, get the list of columns from the current table (uses helper function GetColumns() ). 由于失败,从当前表中获取列的列表(使用辅助函数GetColumns() )。
  3. rename the old table to temp_OLDTABLENAME. 将旧表重命名为temp_OLDTABLENAME。
  4. Create the a new version of the database additional columns (currently empty). 创建数据库附加列的新版本(当前为空)。
  5. get all information from the old version of the database. 从旧版本的数据库中获取所有信息。
  6. insert it into new database 将其插入新数据库
  7. drop the old table (temp_OLDTABLENAME). 删除旧表(temp_OLDTABLENAME)。

I tried to write this generic enough so all i have to do is update DATABASE_UPGRADE with the additional columns and this handles all the rest. 我尝试写这个通用的,所以我所要做的就是用附加列更新DATABASE_UPGRADE,这将处理所有其余的。 It has worked for me through 3 upgrade so far. 到目前为止,它已通过3次升级为我工作。

您可以使用ALTER TABLE添加列。

ALTER TABLE my_table ADD COLUMN location ...;

使用SQLiteOpenHelper的onUpgrade方法运行“alter table”语句。

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

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