从assets文件夹中复制的sqlite数据库如何升级(Android)

7
我使用了这个教程:自定义数据库教程 我从assets文件夹中复制了数据库并将其复制到我的设备(或模拟器)中。一切都正确,我在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;
        }

感谢您能给我一个原因或提示,为什么这不起作用。
6个回答

5

当onUpgrade()函数被调用时,Android已经打开了数据库。我认为此时不可能删除它。查看日志以获取更多信息。如果您想这样做,需要将删除和复制代码移到尚未打开数据库的位置。


是的,你说得对。我使用了共享首选项来签署新版本的数据库,并在使用此对象之前删除了数据库。谢谢。 - kolek
2
@kolek:你能和大家分享解决方案吗?我也需要类似的东西。 - Anand Sainath
为什么不分享解决方案,Kolek?很多人需要它。 - Nguyen Minh Binh
@NguyenMinhBinh请查看这个链接 http://stackoverflow.com/questions/14620429/android-how-to-upgrade-database-from-asset-folder?answertab=votes#tab-top - droid kid
@kolek,能否分享解决方案?我需要它。我正在面临太多的困难来完成这个任务,这非常紧急。 - Erum

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);
}

这段代码只会删除表而不是数据库,我们必须删除旧表并从资源中复制新的数据库或表,否则它将无法正常工作,并在编译时给出类似“数据库已锁定”的错误:PRAGMA journal_mode。 - Gaurav Mandlik

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

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();
}

0
只是一个补充:
在createDataBase()函数中有以下检查;

this.getReadableDatabase();

这个函数检查是否已经有一个给定名称的数据库,如果没有,则创建一个空数据库,以便可以用资产文件夹中的数据库覆盖它。在新设备上,这个功能运行得非常顺畅,但是在一些设备上却不起作用。主要是旧设备。我不知道为什么,但似乎getReadableDatabase()函数不仅获取数据库,而且还打开它。如果你从资产文件夹复制数据库到它上面,它仍然指向一个空数据库,并且会出现表不存在的错误。

因此,为了使其在所有设备上都能正常工作,您应该将其修改为以下行:

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

即使数据库在检查过程中被打开,之后也会被关闭,并且不会再给您带来任何麻烦。

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) {
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接