【问题标题】:Replacing my database on android在android上替换我的数据库
【发布时间】:2016-10-26 22:50:09
【问题描述】:

我正在使用 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 方法。

【问题讨论】:

  • 您是否尝试过将该 SQL 代码放入 execSQL 以查看会发生什么?

标签: android sqlite android-contentprovider sqliteopenhelper


【解决方案1】:

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

不确定如何在 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

【讨论】:

    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 2010-09-22
    相关资源
    最近更新 更多