简体   繁体   English

如何在方法onUpgrade中删除数据库?

[英]How to remove DB in method onUpgrade?

How can i remove file with my database on SQLite in method onUpgrade? 如何使用onUpgrade方法在SQLite上使用数据库删除文件?

I tried: 我试过了:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    context.deleteDatabase(DATABASE_NAME);

    onCreate(db);
}

error: context cannot be resolved. 错误:无法解析上下文。

and second: 第二:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    File dbFile = getDatabasePath("your_db_file_name");
    boolean deleted = dbFile.delete();

    onCreate(db);
}

error: The method getDatabasePath(String) is undefined for the type TestDatabase. 错误:类型TestDatabase的方法getDatabasePath(String)未定义。

You cannot delete the file as it is in use at the point this method is called. 在调用此方法时,不能删除正在使用的文件。

Instead, if you really want to the delete the database run 相反,如果您确实要删除数据库,请运行

File dbFile = getDatabasePath("your_db_file_name");
if(dbFile.exists() && dbFile.delete())
{
    // Create new database if that is what you want to do.
}

Before you actually instantiate the DatabaseHelper object. 在实际实例化DatabaseHelper对象之前。 Without knowing the rest of your code it is hard to give a more detailed solution. 在不了解其余代码的情况下,很难给出更详细的解决方案。

you can create a method to clean the table and call it before you add the new values to it 您可以创建一种方法来清理表并在向其添加新值之前调用它

public void delete_ALL_ROWS()
    {
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();

        String deleteSQL = "DELETE FROM " + DATABASE_TABLE;

        ourDatabase.execSQL(deleteSQL);

        ourHelper.close();
    }

In your onUpgrade function you should simply run the drop table statements 在onUpgrade函数中,您应该只运行drop table语句

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // delete our old table
    db.execSQL("DROP TABLE IF EXISTS " + tableName);

    // create our new table
    onCreate(db);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM