无法在Android sqlite中创建临时表

7

我尝试在安卓设备上创建一个临时表(sqlite)。

以下是代码片段:

// No error - But cannot create TEMP table
database.rawQuery("CREATE TEMP TABLE IF NOT EXISTS tt1 (unread_message int, target varchar)", null);

// Error - android.database.sqlite.SQLiteException: no such table: tt1: , while compiling: INSERT INTO tt1 SELECT count(*), target  FROM messages where read_status=0 and direction=1 GROUP BY target
database.rawQuery("INSERT INTO tt1 SELECT count(*), target  FROM messages where read_status=0 and direction=1 GROUP BY target", null);

创建TEMP TABLE的查询没有错误,但第二个查询却抱怨tt1不存在。我是不是以错误的方式创建了TEMP表?


但是这两个查询在SQLite Manager(Firefox插件)中都可以工作。我已经搜索了“SQL范围”,但仍然不理解什么是“范围问题”。你能告诉我更多关于“范围问题”的信息吗?谢谢。 - mobile app Beginner
难道不应该是 count(target) 吗? - njzk2
1个回答

12

通常情况下,您不应该使用rawQuery来创建表和执行插入操作 - 请尝试使用SQLiteDatabase#execSQL

至少这个例子可以工作:

    SQLiteOpenHelper dummy = new SQLiteOpenHelper(this, "mobileAppBeginner.db", null, 1) {
        @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
        @Override public void onCreate(SQLiteDatabase db) {}
    };

    SQLiteDatabase db = dummy.getWritableDatabase();
    db.execSQL("CREATE TEMP TABLE messages (read_status INTEGER, direction INTEGER, target TEXT)");
    db.execSQL("CREATE TEMP TABLE IF NOT EXISTS tt1 (unread_message int, target varchar)");
    db.execSQL("INSERT INTO tt1 SELECT count(*), target  FROM messages where read_status=0 and direction=1 GROUP BY target");

我们可以将其用于之前创建的数据库吗?实际上,我的数据库中有一些表,如果我需要在运行时使用一个临时表,我该如何使用。这里我已经创建了一个数据库。 - gowri
@gowri 你试过了吗?能够和现有的房间数据库一起使用吗? - vizsatiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接