在android中重命名SQL数据库
当引用数据库表时,我通常使用如下语法:my_database_name.my_table_name
我试图在 Android 中执行相同的操作,但无法理解如何命名数据库。
您会像在 Sqlite3 客户端中一样执行此 SQL 吗?即,
ATTACH "my_database_file" AS my_database_name;
这是我在 onCreate 方法中尝试的内容:
db.execSQL("Attach 'hq_db' AS hq_db;");
但我收到此错误:
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;
如何在事务之外在 Android 上执行 SQL 语句以使其工作?
编辑:它也可能与超类构造函数有关,尽管超类构造函数字符串设置文件名(工作正常)并且似乎没有其他内容:
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;");
}
注意:我已经删除了这段代码,因此它适合我的问题
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 the 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在开始任何类型的事务之前,您需要调用 db.execSQL("ATTACH 'hq_db' AS hq_db;");。先做附件,再开始交易。
您是否在尝试附加其他数据库之前调用
beginTransaction
或执行开始事务的 SQL?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?您可能正在使用 AutoCommit=0 创建数据库。这会将您置于一个事务中,这样就不需要在每次插入后写入数据库文件。但这也意味着您无法附加到另一个数据库。创建数据库,设置 AutoCommit=1,ATTACH,然后设置 AutoCommit=0。
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.