我已发布现有应用,并且我想将位置坐标字段添加到sqlite数据库。
我想知道是否可以在不在数据库中创建新表的情况下执行此操作。我不想覆盖用户现有的数据库条目,我只想为现有的数据库条目添加这个新字段并给它一个默认值。
这可能吗?
答案 0 :(得分:10)
是的,
更新表格时需要编写onUpgrade()
方法。目前,我使用以下内容创建一个包含新列的新表,并复制我当前的所有数据。希望您可以根据您的代码进行调整。
@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();
}
这包含onUpgrade()
和两个辅助方法。 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)";
关于这是如何工作的快速说明:
onUpgrade()
。GetColumns()
)。我试着把这个通用写得足够,所以我要做的就是用附加列更新DATABASE_UPGRADE,然后处理所有其余的。到目前为止,它已经通过3次升级为我工作。
答案 1 :(得分:1)
您可以使用ALTER TABLE添加列。
ALTER TABLE my_table ADD COLUMN location ...;
答案 2 :(得分:1)
使用SQLiteOpenHelper的onUpgrade方法运行“alter table”语句。