在Android中更新Sqlite数据库(从现有创建的数据库,无需查询)

时间:2014-08-26 06:48:05

标签: android database sqlite

我已经有Sqlite个数据库,我在Android中使用它。现在,我想在Sqlite数据库中更新下一版Android的数据。所以,我在数据库中输入数据并将其复制到asset文件夹中。

那么我需要在代码中做些什么改变?

我的代码:

public class DatabaseHandler extends SQLiteOpenHelper {

    private static String TAG = "DatabaseHandler";
    private static String DB_PATH = "";
    private static String DB_NAME = "dbJeeten";
    private SQLiteDatabase mDataBase;
    private final Context mContext;

    public DatabaseHandler(Context context) {
        super(context, DB_NAME, null, 1);// 1? its Database Version
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        this.mContext = context;
    }

    public void createDataBase() throws IOException {

        boolean mDataBaseExist = checkDataBase();
        if (!mDataBaseExist) {
            this.getReadableDatabase();
            this.close();

            try {
                copyDataBase();
                Log.e(TAG, "createDatabase database created");
            } catch (IOException mIOException) {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    private void copyDataBase() throws IOException {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;

        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }

        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public boolean openDataBase() throws SQLException {
        String mPath = DB_PATH + DB_NAME;

        mDataBase = SQLiteDatabase.openDatabase(mPath, null,
                SQLiteDatabase.CREATE_IF_NECESSARY);

        return mDataBase != null;
    }

    @Override
    public synchronized void close() {
        if (mDataBase != null)
            mDataBase.close();
        super.close();
    }

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

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
if (newVersion > oldVersion) {
        mContext.deleteDatabase(DB_NAME);
    }
    }
}


我希望当用户更新应用程序时,数据库会自行更新。

错误:

android.database.sqlite.SQLiteException: cannot rollback - no transaction is active


我需要做些什么改变?

0 个答案:

没有答案