无法在事务内附加数据库

Ash*_*ari 5 sqlite android android-sqlite

我正在开发一个必须使用两个数据库的应用程序。我想将新数据库表中的记录添加到旧数据库表中,我已将新数据库放在项目的资产文件夹中,并且可以使用新数据库和旧数据库进行查询。

问题是当我尝试在方法上将新数据库附加到旧数据库时,发生了无法在事务中附加数据库的onUpgrade()错误。

我发现很多链接都有这个问题,我已经尝试了很多但没有成功。我是 Android 新手SQLite,请告诉我如何在代码中附加数据库和另一个数据库。

数据库助手类: DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
Context context;
SQLiteDatabase sourceDatabase;
private String TAG = this.getClass().getSimpleName();

private static final String DATABASE_NAME = "namesdemo_db";
private static final String SOURCE_DB_NAME = "namesdemo_db_s";
private static final int DATABASE_VERSION = 23;

private String DATABASE_PATH;
File dbFile;

// TABLE NAMES
private static final String TABLE_EMPLOYEE = "employee";
private static final String TABLE_FAVORITE = "fevorite";

// KEYS of Table Employee
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_ADDRESS = "address";

// Keys of Table Fevorite
private static final String KEY_FEV_ID = "fev_id";
// private static final String KEY_ID = "id";

private static final String CREATE_TBL_EMPLOYEE = "CREATE TABLE " + TABLE_EMPLOYEE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME
        + " TEXT," + KEY_ADDRESS + " TEXT)";
private static final String CREATE_TBL_FEVORITE = "CREATE TABLE " + TABLE_FAVORITE + "(" + KEY_FEV_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ID
        + " INTEGER )";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
    this.context = context;
    DATABASE_PATH = "/data/data/" + context.getApplicationContext().getPackageName() + "/databases/";

    Log.v(TAG, " DB Path " + DATABASE_PATH);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    Log.v(TAG, CREATE_TBL_EMPLOYEE);

    db.execSQL(CREATE_TBL_EMPLOYEE);

    db.execSQL(CREATE_TBL_FEVORITE);

    Log.v(TAG, " OnCreate Executed");

}

private void copyDataBase(String dbPath) {
    try {
        InputStream assestDB = context.getAssets().open(SOURCE_DB_NAME);

        OutputStream appDB = new FileOutputStream(dbPath + SOURCE_DB_NAME, false);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = assestDB.read(buffer)) > 0) {
            appDB.write(buffer, 0, length);
        }

        appDB.flush();
        appDB.close();
        assestDB.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.v(TAG, " copyDataBase() called");

}

public long createName(String name, String address) {
    long count = 0;
    SQLiteDatabase db = getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name);
    values.put(KEY_ADDRESS, address);
    count = db.insert(TABLE_EMPLOYEE, null, values);
    db.close();
    Log.v(TAG, +count + " row(s) inserted!");
    return count;
}

public long createFevorite(int id) {
    long count = 0;
    SQLiteDatabase db = getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_ID, id);
    count = db.insert(TABLE_FAVORITE, null, values);
    db.close();
    Log.v(TAG, +count + " row(s) inserted in " + TABLE_FAVORITE);
    return count;
}

public List<Employee> getAllNames() {
    List<Employee> nameList = new ArrayList<Employee>();
    String query = "Select * from " + TABLE_EMPLOYEE;

    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.rawQuery(query, null);
    if (c.moveToFirst()) {
        do {
            Employee e = new Employee();
            e.setID(c.getInt(c.getColumnIndex(KEY_ID)));
            e.setName(c.getString(c.getColumnIndex(KEY_NAME)));
            e.setAddress(c.getString(c.getColumnIndex(KEY_ADDRESS)));
            nameList.add(e);

        } while (c.moveToNext());
    }
    return nameList;
}

public List<Employee> getAllNames(SQLiteDatabase db) {
    List<Employee> nameList = new ArrayList<Employee>();
    String query = "Select * from " + TABLE_EMPLOYEE;

    Cursor c = db.rawQuery(query, null);
    if (c.moveToFirst()) {
        do {
            Employee e = new Employee();
            e.setID(c.getInt(c.getColumnIndex(KEY_ID)));
            e.setName(c.getString(c.getColumnIndex(KEY_NAME)));
            e.setAddress(c.getString(c.getColumnIndex(KEY_ADDRESS)));
            nameList.add(e);

            Log.v(TAG, "ID: " + e.getID());
            Log.v(TAG, "NAme: " + e.getName());
            Log.v(TAG, "Address" + e.getAddress());

        } while (c.moveToNext());
    }

    return nameList;
}

private boolean checkDatabase() {
    // SQLiteDatabase checkdb = null;
    boolean checkdb = false;
    try {
        String myPath = DATABASE_PATH + SOURCE_DB_NAME;
        File dbfile = new File(myPath);
        // checkdb =
        // SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
        checkdb = dbfile.exists();
    } catch (SQLiteException e) {
        System.out.println("Database doesn't exist");
    }
    return checkdb;
}

public void openDatabase() throws SQLException {
    String path = DATABASE_PATH + "namesdemo_db_s";
    sourceDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
    Log.v(TAG, " openDatabase() called ");
}

public synchronized void closeDatabase() {
    if (sourceDatabase != null) {
        sourceDatabase.close();
        Log.v(TAG, " closeDatabase() called ");
    }
    super.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    String drop_tbl = "DROP TABLE " + TABLE_EMPLOYEE;
    String attach_db = "ATTACH DATABASE '" + SOURCE_DB_NAME + "' AS 'temp_db'";
    String create_table = "CREATE TABLE " + TABLE_EMPLOYEE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_ADDRESS
            + " TEXT)";
    String insert = "INSERT INTO " + TABLE_EMPLOYEE + "(" + KEY_ID + "," + KEY_NAME + "," + KEY_ADDRESS + ") SELECT * FROM temp_db." + TABLE_EMPLOYEE;

    boolean dbExists = checkDatabase();
    if (dbExists) {

        Log.v(TAG, " DB  exists");

        // getAllNames(sourceDatabase);
    } else {
        Log.v(TAG, " DB does not exists");
        copyDataBase(DATABASE_PATH);
        // openDatabase();
        // getAllNames(sourceDatabase);
    }
    db.execSQL(attach_db);
    openDatabase();
    //db.endTransaction();
    db.execSQL(drop_tbl);
    db.execSQL(create_table);

    db.execSQL(insert);

    Log.v(TAG, " onUpgrade() Executed");

    db.close();
    sourceDatabase.close();

}
Run Code Online (Sandbox Code Playgroud)

}

小智 0

您的库可能包含一个错误,它执行 BEGIN TRANSACTION (以提高性能和/或锁定数据库),但不执行 END TRANSACTION 来释放锁。

例子:

> sqlite3 database.sqlite
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> ATTACH DATABASE 'database.sqlite.old' AS old_db;    -- works
sqlite> DETACH DATABASE old_db;
sqlite> BEGIN TRANSACTION;                                  -- lock db
sqlite> ATTACH DATABASE 'database.sqlite.old' AS old_db;    -- fails
Error: SQL logic error or missing database
sqlite> END TRANSACTION;                                    -- release lock
sqlite> ATTACH DATABASE 'database.sqlite.old' AS old_db;    -- works
sqlite> DETACH DATABASE old_db;
Run Code Online (Sandbox Code Playgroud)