Renaming an SQL database in android
When referring to database tables I usually use syntax like this: my_database_name.my_table_name
I am trying to do the same in Android but am having trouble understanding how to name a database.
Would you just execute this SQL as you would in the Sqlite3 client? i.e.
ATTACH "my_database_file" AS my_database_name;
Here is what I tried in my onCreate method:
db.execSQL("Attach 'hq_db' AS hq_db;");
but I'm getting this error:
04-05 11:13:35.676: ERROR/AndroidRuntime(860): Caused by: android.database.sqlite.SQLiteException: cannot ATTACH database within transaction: Attach 'hq_db' AS hq_db;
How do I execute SQL statements on Android outside of a transaction to make this work?
Edit: It might also have something to so with the superclass constuctor, though th开发者_运维技巧e super class constructor string sets the file name (which is working properly) and it seems nothing else:
private class databaseOpenHelper extends SQLiteOpenHelper {
public q_player_databaseOpenHelper() {
super(MyApp.getContext(), "my_db_file", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Attach 'my_db_file' AS my_db_name;");
db.execSQL("PRAGMA foreign_keys=ON;");
}
Note: I have stripped this code down so it would fit my problem
You need to call db.execSQL("ATTACH 'hq_db' AS hq_db;");
before you start any kind of transaction. Do the attachment first, and then start the transaction.
Are you calling beginTransaction
or executing SQL which begins a transaction before trying to attach your other database?
You're probably creating the database with AutoCommit=0. This puts you in a transaction so that it doesn't need to write to the database file after every INSERT. But it also means you can't ATTACH to another database. Create the DB, set AutoCommit=1, ATTACH, then set AutoCommit=0.
精彩评论