Android sqlite无法创建TEMP表

时间:2016-10-06 13:02:20

标签: android sqlite temporary

我想在android sqlite数据库中创建和使用临时表 执行SQL语句时没有任何异常,但没有创建表! 使用下面的示例代码运行我的应用程序,我没有表格:

START EDIT

func containerURL(forSecurityApplicationGroupIdentifier groupIdentifier: String) -> URL?

结束编辑

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "mydb.db";
private static DatabaseHelper instance;

public static synchronized DatabaseHelper getHelper(Context context){
    if (instance == null)
        instance = new DatabaseHelper(context);
    return instance;
}

private DatabaseHelper(Context c) {
    super(c,DB_NAME,null,1);
}

@Override
public void onConfigure(SQLiteDatabase db) {
    super.onConfigure(db);
    db.enableWriteAheadLogging ();
    db.setLocale(Locale.getDefault());
}

@Override
public void onCreate(SQLiteDatabase db) {
    // lots of table creation
    db.execSQL("CREATE TABLE my_table (id INTEGER PRIMARY KEY, value TEXT)");
    // more tables ....
}}
...... sample 
DatabaseHelper databaseHelper = DatabaseHelper.getHelper(this);

如果我从select语句创建一个临时表,然后查询(在同一个数据库连接中)创建的表,我得到“没有这样的表....异常”!

SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("create TEMP table my_temp_table (id integer primary key, value text)"); // no exceptions

Cursor cursor = db.query("SQLITE_TEMP_MASTER", null, null, null, null, null, null);

while( cur.moveToNext()) {
    // no lines (no temporary tables)
}

让我感到困惑的是......相同的SQL代码在SQLiteStudio中完美运行,即在应用程序之外和Android设备之外。 也许我忘了启用某些东西或......我需要特定的设备权限?

2 个答案:

答案 0 :(得分:1)

使用db.enableWriteAheadLogging()启用预写日志记录时,SQLiteDatabase会自动多路复用数据库连接。用于db.query(...)的连接与用于db.execSQL("CREATE TEMP TABLE ...")的连接不同。

您可以在事务中包装db.query(...)并强制SQLiteDatabase使用与execSQL相同的连接。

db.beginTransaction();
Cursor cursor = db.query("temp.my_temp_table", null, null, null, null, null, null);
try {
    while (cursor.moveToNext()) {
        // ...
    }
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}

答案 1 :(得分:0)

create temp table x的结果是表格x而不是temp.x

更改您的代码以使用my_temp_table

相关问题