游标在“查询、删除表、创建表、查询相同表名”后返回相同的列

2024-05-12

例如我有一个名为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顺序


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

游标在“查询、删除表、创建表、查询相同表名”后返回相同的列 的相关文章

随机推荐