如何在更新应用程序时用新的数据库替换我的sqlite数据库?

时间:2016-12-20 00:35:55

标签: android database sqlite sqliteopenhelper

如何在不需要卸载我的Android应用程序的情况下更新我的sqlite数据库。我使用名为' Sqlite Expert' ...的数据库管理器构建我的数据库,并将结果复制到我项目的assets文件夹中。 这是我的Database.java来做数据库工作:

public class Database extends SQLiteOpenHelper {

private static final String dbInstallationPath = "/data/data/com.example.asus.android/databases/";
private static final String dbName = "database";
private static final int dbVersion = 2;
private final Context mycontext;
public SQLiteDatabase mydb;


public Database(Context context) {
    super(context, dbName, null, dbVersion);
    mycontext = context;
}


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

    Log.d("oncreate", "oncreated was called..s");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + "content");
    onCreate(db);
    try {
        copydatabase();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d("databaseupdate", "db was updaatedd.");
}


public void usable() {
    if (checkdb()) {
    } else {
        this.getReadableDatabase();
        try {
            copydatabase();
            Log.d("copy successful", "conpy done! dsyccesful...");
        } catch (IOException e) {
            Log.d("copydatabase()", "IOExcptons fFor copyyingdatabasde");
        }
    }
    Log.d("usable", "usable called.");
}

public void open() {
    mydb = SQLiteDatabase.openDatabase(dbInstallationPath + dbName, null, SQLiteDatabase.OPEN_READWRITE);
}

public void close() {
    mydb.close();
}

public boolean checkdb() {

    SQLiteDatabase db = null;
    try {
        db = SQLiteDatabase.openDatabase(dbInstallationPath + dbName, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e) {
        Log.d("new", "the database coudlnt be opened..fghf");

    }

    return db != null ? true : false;

}


public void copydatabase() throws IOException {
    OutputStream myOutput = new FileOutputStream(dbInstallationPath + dbName);
    byte[] buffer = new byte[1024];
    int length;
    InputStream myInput = mycontext.getAssets().open(dbName);
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    myInput.close();
    myOutput.flush();
    myOutput.close();

}

my database in assets folder

0 个答案:

没有答案