Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create TEMP table in Android sqlite

I have tried to create a temporary table (sqlite) in Android

Here is the code snippet:

// 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);

There is no error for the create TEMP TABLE query, but it complains tt1 is not existed in the second query. Am I create TEMP table in a wrong way?

like image 222
mobile app Beginner Avatar asked Mar 08 '12 15:03

mobile app Beginner


1 Answers

Typically you shouldn't be using rawQuery for creating tables and doing inserts - try using SQLiteDatabase#execSQL.

This example works at least:

    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");
like image 144
Jens Avatar answered Sep 19 '22 17:09

Jens