例如我有一个名为myTable
在我的数据库文件中(Android,ps它不支持列重命名,删除等)。
这张表有idx
, name
columns
我想删除并重新创建该表,但使用新列
我是这样做的:
db.transaction {
var cursor = query("myTable", null, null, null, null, null, null)
// save info to a list and insert it later to a recreated table with new columns
cursor.close()
// delete table "myTable"
execSQL("DROP TABLE IF EXISTS myTable")
// create table "myTable" but with new columns
execSQL("CREATE TABLE myTable(id, title)")
// get columns
cursor = query("myTable", null, null, null, null, null, null)
val columnNames = cursor.columnNames
cursor.close()
Log.i(TAG, "columns of new table ${Arrays.toString(columnNames)}")
}
But cursor.columnNames
不返回新列(id
, title
)
它返回旧列(例如,idx
, name
)
虽然当我关闭应用程序并再次打开时一切正常(旧列消失,新列可用)
很烦人!
所以新的列就创建好了main.db/myTable
在整个过程中,但应用程序似乎仍将旧列保留在内存中
我什至无法使用cursor.getString(cursor.getColumnIndex("title"))
(将返回-1
)因为它仍然认为该列尚不存在,直到我重新启动此应用程序
但!如果我不使用,用新列重新创建表效果很好cursor
在删除旧表之前备份数据(信息)
db.transaction {
// !! I COMMENTED THESE LINES
// var cursor = query("myTable", null, null, null, null, null, null)
// save info to a list and insert it later to a recreated table with new columns
// cursor.close()
// delete table "myTable"
execSQL("DROP TABLE IF EXISTS myTable")
// create table "myTable" but with new columns
execSQL("CREATE TABLE myTable(id, title)")
// get columns
cursor = query("myTable", null, null, null, null, null, null)
val columnNames = cursor.columnNames
cursor.close()
Log.i(TAG, "columns of new table ${Arrays.toString(columnNames)}")
}
在这种情况下cursor.columnNames
返回新列id
, title
这太疯狂了!
所以它看起来query table1
, drop table1
, create table1
, query table1
顺序会导致意外的行为
而我们只能做drop table1
, create table1
, query table1
顺序