gpt4 book ai didi

android - 使用 SQLiteOpenHelper 在 Android 中附加 sqlite 数据库

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:54 26 4
gpt4 key购买 nike

我正在创建一个引用另一个数据库中的键的数据库。本质上,我有一个数据导入,我想将这些数据与将要更改的数据分开,但如果可能的话,我想通过 FOREIGN KEY 引用其他键。据我所知,我需要先附加数据库才能实现。到目前为止,这是相关代码:

public class LogDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "log.db";
private static final int DATABASE_VERSION = 1;
private String namesDb;

public LogDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
namesDb=getNamesDbPath();

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("ATTACH DATABASE ? AS names",new String[]{namesDb});
StringBuilder query=new StringBuilder();
query.append("CREATE TABLE log (");
}
}

但是,这似乎不起作用,因为我收到以下错误:

11-21 17:35:58.176: E/SQLiteLog(9984): (1) statement aborts at 5: [ATTACH DATABASE ? AS names] cannot ATTACH database within transaction
11-21 17:35:58.176: D/AndroidRuntime(9984): Shutting down VM
11-21 17:35:58.176: W/dalvikvm(9984): threadid=1: thread exiting with uncaught exception (group=0x41a21700)
11-21 17:35:58.191: E/AndroidRuntime(9984): FATAL EXCEPTION: main
11-21 17:35:58.191: E/AndroidRuntime(9984): android.database.sqlite.SQLiteException: cannot ATTACH database within transaction (code 1)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:734)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
11-21 17:35:58.191: E/AndroidRuntime(9984): at com.kd7uiy.hamfinder.LogDatabaseHelper.onCreate(LogDatabaseHelper.java:27)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
11-21 17:35:58.191: E/AndroidRuntime(9984): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)

我怎样才能让它工作?

最佳答案

我找到了一种让它发挥作用的方法,虽然我并不为此感到特别自豪,但它确实起到了作用。如果在附加数据库时不能处于事务中,则先结束事务。

db.setTransactionSuccessful();
db.endTransaction();
db.execSQL("ATTACH DATABASE ? AS names",new String[]{namesDb});
db.beginTransaction();

关于android - 使用 SQLiteOpenHelper 在 Android 中附加 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com