升级我从资产文件夹(Android)复制的sqlite数据库
我使用本教程: 我将数据库从assets文件夹复制到我的设备(或emulator)。一切都是正确的。我在DDMS透视图中看到我的数据库。但我有时也想升级我的数据库,所以我做到了:升级我从资产文件夹(Android)复制的sqlite数据库,android,sqlite,Android,Sqlite,我使用本教程: 我将数据库从assets文件夹复制到我的设备(或emulator)。一切都是正确的。我在DDMS透视图中看到我的数据库。但我有时也想升级我的数据库,所以我做到了: super(context, DB_NAME, null, 2); //changed version from 1 to 2 并修改onUpgrade方法: @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVers
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;
}
如果你能给我一个原因或者仅仅是一个提示,那就谢谢你了。当函数onUpgrade()被调用时,android已经打开了数据库。我认为现在不可能删除它。查看日志了解更多信息。如果你想这样做,你需要把删除和复制代码移到数据库还没有打开的地方。试试这个代码……我想它会解决你的问题
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);
}
您可以在升级数据库之前删除旧数据库
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();
}
只是一个补充:
在createDataBase()中有以下检查:
这是.getReadableDatabase()
这将检查是否已经存在具有所提供名称的数据库,如果没有,将创建一个空数据库,以便可以使用资产文件夹中的数据库覆盖该数据库。在较新的设备上,这可以完美地工作,但也有一些设备无法工作。主要是老式设备。我不知道确切的原因,但getReadableDatabase()函数似乎不仅可以获取数据库,还可以打开它。如果您随后将数据库从资产文件夹复制到它上面,它仍然有指向空数据库的指针,并且您将得到表不存在错误
因此,为了使其在所有设备上工作,您应该将其修改为以下行:
SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
db.close();
}
即使在检查中打开了数据库,它也会在检查后关闭,不会给您带来任何麻烦。从资产复制数据库时,默认情况下版本为0。 在从资产复制数据库的方法中,使用数据库对象的方法
setVersion(int-version)
设置其版本。
如果数据库存在,则通过数据库对象上的方法
getVersion()
检查其版本。现在自己处理它的onUpgrade,即如果db evrsion已更新noe,则升级数据库,然后setVersion(int new dbVersion)
主要思想是在创建新数据库时,您应该使用SharedReferences存储数据库版本。之后,在创建数据库时,必须检查数据库是否有新版本,然后删除旧数据库并创建新数据库
这个代码对我有用
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) {
}
}
是的,你说得对。我做了什么?我使用共享首选项对数据库的新版本进行签名,并在使用此对象之前删除数据库。谢谢。@kolek:你能和大家分享解决方案吗?我也需要类似的东西。你为什么不分享解决方案呢,科莱克?请,很多人都需要它。@Nguyenmininh检查一下这个@kolek can u pleasen share解决方案我需要这个我做这项任务有太多的困难非常紧迫这段代码将只删除表而不是数据库,我们必须删除旧表并从资产中复制新的数据库或表,这将不起作用,编译时,它会给您类似于数据库被锁定的错误:PRAGMA journal\u模式