android - 从 sqlite 数据库中删除所有表

标签 android database sqlite

我做了很多研究,但找不到合适的方法来删除 SQLite 数据库中的所有表。最后,我编写了一个代码来从数据库中获取所有表名,并且我尝试使用检索到的表名一个一个地删除这些表。它也没有奏效。

请建议我一种从数据库中删除所有表的方法。

这是我使用的代码:

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());
}

function deleteall() 在按钮点击时被调用,代码如下:

public void ButtonClick(View view)
{
    String Button_text;
    Button_text = ((Button) view).getText().toString();

    if(Button_text.equals("Delete Database"))
    {
        DatabaseHelper a = new DatabaseHelper(this);
        a.deleteall();
        Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
    }}

最佳答案

使用DROP TABLE:

// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();

// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
    tables.add(c.getString(0));
}

// call DROP TABLE on every table name
for (String table : tables) {
    String dropQuery = "DROP TABLE IF EXISTS " + table;
    db.execSQL(dropQuery);
}

关于android - 从 sqlite 数据库中删除所有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672579/

相关文章:

java - 条形码扫描仪使用 ML Kit 仅读取 QR 码

android - relativelayout、include 和layout_alignParentBottom 不起作用

mysql - MySQL中特定数据库约束的解决方案

python - 将未知数插入 SQLite 数据库

sqlite - 运行时错误 : invalid memory address or nil pointer dereference when Querying

java - 在 Eclipse 中创建包含资源的 JAR 文件。

android - 如果我更改 Play 商店的类别, 'Similar apps' 部分会发生什么情况?

Python 编码 - 无法解码为 utf8

mysql - 使用 join MySQL 时字段列表中的未知列

c++ - 并行线程中的数据库访问,可行的选择?