7

我使用本教程: 教程自定义数据库

我从资产文件夹复制数据库并将其复制到我的设备(或模拟器)。一切都是正确的。我从 DDMS 的角度来看我的数据库。但我有时也想升级我的数据库,所以我做了:

super(context, DB_NAME, null, 2); //changed version from 1 to 2

并修改 onUpgrade 方法:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if(newVersion > oldVersion){
        this.myContext.deleteDatabase(DB_NAME);
        try {
            this.copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但运行后,我的设备上仍有旧版本的数据库。如何删除旧版本的数据库并复制新版本。DB_NAME 是我的数据库名称(带格式,但不带路径), copyDataBase() 是将数据库复制到设备的方法(它可以工作)。

我粘贴我的所有代码:

public class DataBaseHelper extends SQLiteOpenHelper{

    private static String DB_PATH = "/data/data/sitcom.quiz/databases/";

    private static String DB_NAME = "sitcoms.sqlite";

    private SQLiteDatabase myDataBase; 

    private final Context myContext;

    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 4);
        this.myContext = context;
    }   

    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){
            //database does't exist yet.
        }

        if(checkDB != null){
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }


    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("adas", "dasd");

        if(newVersion > oldVersion){
            String myPath = DB_PATH + DB_NAME;
            this.myContext.deleteDatabase(myPath);
            try {
                this.copyDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

和我的活动:

DataBaseHelper myDbHelper = new DataBaseHelper(this);
        myDbHelper = new DataBaseHelper(this);

        try {
            myDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        try {
            myDbHelper.openDataBase();
        }catch(SQLException sqle){
            throw sqle;
        }

谢谢,如果你能给我理由或只是暗示为什么这不起作用。

4

6 回答 6

5

调用函数 onUpgrade() 时,android 已经打开了数据库。我认为目前无法删除它。检查日志以获取更多信息。如果你想这样做,你需要将删除和复制代码移动到数据库尚未打开的地方。

于 2012-06-08T23:36:23.623 回答
2

试试这个代码......我认为它会解决你的问题。

public void onUpgrade(SQLiteDatabase database, int oldVersion,
        int newVersion) {
    Log.w(DatabaseHelper.class.getName(),
            "Upgrading database from version " + oldVersion  + " to "
                    + newVersion + ", which will destroy all old data");
    database.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
    onCreate(database);
}
于 2012-07-18T13:06:36.673 回答
1

从资产复制数据库时,默认版本为 0。在从资产复制数据库的方法中,使用setVersion(int version)数据库对象的方法设置其版本。如果 db 存在,则通过getVersion()数据库对象上的方法检查其版本。现在自己处理它的 onUpgrade ,即如果 db evrsion 已更新 noe,则升级数据库,然后setVersion(int new dbVersion).

于 2015-04-27T06:29:31.330 回答
0

您可以在升级数据库之前删除旧数据库。

    if(dbExist){
                Log.v("com.db","db exists");
                myContext.deleteDatabase(DB_NAME);`enter code here`
                //openDataBase();
                //do nothing - database already exist
            }else{
                Log.v("com.db","dbnot exists");
                //By calling this method and empty database will be created into the default system path
                   //of your application so we are gonna be able to overwrite that database with our database.
                this.getReadableDatabase();
}
于 2013-04-17T06:59:52.870 回答
0

只是一个补充:

在 createDataBase() 中有以下检查;

this.getReadableDatabase();

这将检查是否已经存在具有所提供名称的数据库,如果没有,则创建一个空数据库,以便可以用 assets 文件夹中的数据库覆盖它。在较新的设备上,这可以完美运行,但在某些设备上这不起作用。主要是旧设备。我不知道确切原因,但似乎 getReadableDatabase() 函数不仅获取数据库而且还打开它。如果您随后从 assets 文件夹中复制数据库,它仍然具有指向空数据库的指针,您将收到 table does not exist 错误。

因此,为了使其适用于所有设备,您应该将其修改为以下几行:

SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
    db.close();
}

即使在检查中打开了数据库,之后也关闭了,也不会给你带来任何麻烦。

于 2013-07-20T23:18:10.090 回答
0

主要思想是您应该在创建新数据库时使用SharedPreferences来存储数据库版本。
之后,当您创建数据库时,您必须检查数据库是否有新版本,然后删除旧数据库并创建新数据库
此代码适用于我

private static class DatabaseHelper extends SQLiteOpenHelper {

        private static final String DATABASE_NAME = "database.name";
        private static final int DATABASE_VERSION = 1;
        private static final String KEY_DB_VER = "database_version";
        private final Context mContext;

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            mContext = context;
            initialize();
        }

        /**
         * Initializes database. Creates database if doesn't exist.
         */
        private void initialize() {
            if (databaseExists()) {
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(mContext);
                int dbVersion = prefs.getInt(KEY_DB_VER, 1);
                //
                if (DATABASE_VERSION != dbVersion) {
                    File dbFile = mContext.getDatabasePath(DATABASE_NAME);
                    // delete the old databse   
                    if (!dbFile.delete()) {
                        Log.w(TAG, "Unable to update database");
                    }
                }
            }
            // create database if needed
            if (!databaseExists()) {
                createDatabase();
            }
        }

        /**
         * Returns true if database file exists, false otherwise.
         * @return
         */
        private boolean databaseExists() {
            File dbFile = mContext.getDatabasePath(DATABASE_NAME);
            return dbFile.exists();
        }

        public void createDataBase() throws IOException {
            // If database not exists copy it from the assets
            boolean mDataBaseExist = databaseExists();

            if (!mDataBaseExist) {
                this.getReadableDatabase();
                this.close();
                try {
                    // Copy the database from assests
                    copyDataBase();

                    //**save the database version by SharedPreferences**

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(mContext);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(KEY_DB_VER, DATABASE_VERSION);
                    editor.commit();

                    Log.e(TAG, "createDatabase database created");

                } catch (IOException mIOException) {
                    throw new Error("ErrorCopyingDataBase");
                }
            }
        }

        // Copy the database from assets
        private void copyDataBase() throws IOException {
            Log.i("TAG", "copy database");
            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();
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
                int newVersion) {
        }
    }
于 2015-08-05T02:42:34.647 回答