在android上替换我的数据库

时间:2016-10-26 22:50:10

标签: android sqlite android-contentprovider sqliteopenhelper

我正在使用ContentProvider。我的SQLiteOpenHelper类包含方法

public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + table1);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + table2);
        onCreate(sqLiteDatabase);
    }

说我处在一种我不记得桌子名称的情况下(我以某种方式丢失了它们。和我一起玩)。如何从方法onUpgrade中删除所有这些内容?我看到提到

PRAGMA writable_schema = 1;
delete from sqlite_master where type in ('table', 'index', 'trigger');
PRAGMA writable_schema = 0;

但我不知道如何将其应用于onUpgrade方法。

1 个答案:

答案 0 :(得分:3)

您可以在升级方法中编写以下代码。

不确定如何在onUpgrade中使用drop table查询。

试试这个希望您可以通过使用以下代码获得任何想法。

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String alterTableQuery = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COULMN_NAME + " INT DEFAULT 0 ";
        db.execSQL(alterTableQuery);
    }

还有一种方法可以使用drop all table替换数据库,然后调用onCreate方法。

您可以使用以下代码。

public void deleteall(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    do
    {
        db.delete(c.getString(0),null,null);
    }while (c.moveToNext());
}

Delete all tables from sqlite database

相关问题