How do i upgrade my pre-populated sqlite database

2019-08-17 13:12发布

问题:

I have my code below. It correctly reads my sqlite database file(that i have already created using the SQLite Database Browser) in my assets folder - moves it to the /data/data/packagename/databases/ path on my device then i am able to use a query and cursor to get my information and it works great. Code here:

public class DatabaseHelper extends SQLiteOpenHelper {

private Context myDbContext;
private static String dbName = "restaurant.db";
private static String outfilePath = "/data/data/dev.mypackage.com/databases/";
private static String path = outfilePath + dbName;
private static SQLiteDatabase db;

public DatabaseHelper(Context context){
    super(context, dbName, null, 2);
    this.myDbContext = context;
    db = openDb();
    String s = "select * from menu";
    Cursor c = db.rawQuery(s, null);
    Log.e("DB Constructor Row count", String.valueOf(c.getCount()).toString());

    while(c.moveToNext()){
        Log.e("DB Constructor", c.getString(c.getColumnIndex("category")));
        Log.e("DB Constructor", c.getString(c.getColumnIndex("menuItem_id")));
        Log.e("DB Constructor", c.getString(c.getColumnIndex("title")));
        Log.e("DB Constructor", c.getString(c.getColumnIndex("desc")));
        Log.e("DB Constructor", c.getString(c.getColumnIndex("price")));
        Log.e("DB Constructor", c.getString(c.getColumnIndex("icon")));
    }

    c.deactivate();
    c.close();
}

private void copyDataBase(File dbFile) throws IOException {
    try{
        InputStream dbStream = myDbContext.getAssets().open(dbName);
        OutputStream newDbFile = new FileOutputStream(outfilePath + dbName);

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

        newDbFile.flush();
        newDbFile.close();
        dbStream.close();
    }
    catch(IOException e){

        throw new IOException("trying to copy the database - ERROR: " + e.getMessage());
    }   

}

private SQLiteDatabase openDb() throws SQLiteException{
    File dbFile = myDbContext.getDatabasePath(dbName);

    if(!dbFile.exists()){
        Log.e("openDb", "file does not exist");

        try {
            copyDataBase(dbFile);
        } catch (IOException e) {
            throw new RuntimeException("Error creating source database", e);
        }
    }

    return SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);

}
public void loadRestaurantInfo(){

}

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

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

Now i had to go back and add a row of information to one of the tables(in the database in the assets folder), using the SQLite Brower, - but that is not being reflected in my cursor output - I understand why this is happening - because if(!dbFile.exists()) fails so there is no copying to be done. So my question is - is what code do i need to add to make this work? I never created the tables with code so i dont see how useful the onUpgrade method is going to be for me.

回答1:

You have three options:

  1. Use onUpgrade() (preferred)

  2. Delete the existing database and copy the new one (not a good idea)

  3. Copy the data in the existing database, delete the existing database, copy the new database, insert data from old database into new database (too much work when the new database schema can be upgraded in onUpgrade).

So, to answer your question, you upgrade your database in onUpgrade() without having to recreate any tables.

On the other hand, if you just added a new row to a particular table, the database schema has not changed and you can just insert the new row at runtime... of course, not knowing what your application's purpose is this may not be a good idea as you can easily lose track of changes to your "static" database.



回答2:

The "right" way to do things is quite different from how you've set out. Rather than go there, I'll assume you want to keep your current method of creating your database and I'll offer a suggestion to work with it. Add a table to your database which has a single row of meta data, which will include the database version (as well as anything else you like). If the database file already exists, open it and check the version. If the version is old, close it and replace it.