当前位置:首页 > 数据库 > SQlite

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

按钮单击时调用函数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);
}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!