我做了很多研究,但无法找到合适的方法来删除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();
}}
答案 0 :(得分:21)
使用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);
}
答案 1 :(得分:4)
Tim Biegeleisen's answer几乎为我工作,但因为我在表中使用了AUTOINCREMENT
个主键,所以有一个名为sqlite_sequence
的表。当例程试图删除该表时,SQLite会崩溃。我也抓不到异常。看看https://www.sqlite.org/fileformat.html#internal_schema_objects,我了解到可能有几个内部架构表,我不应该放弃。文档说任何这些表的名称都以 sqlite _ 开头,所以我写了这个方法
private void dropAllUserTables(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
//noinspection TryFinallyCanBeTryWithResources not available with API < 19
try {
List<String> tables = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
tables.add(cursor.getString(0));
}
for (String table : tables) {
if (table.startsWith("sqlite_")) {
continue;
}
db.execSQL("DROP TABLE IF EXISTS " + table);
Log.v(LOG_TAG, "Dropped table " + table);
}
} finally {
cursor.close();
}
}
答案 2 :(得分:1)
删除数据库而不是删除表,然后根据需要创建具有相同名称的新数据库。使用以下代码
context.deleteDatabase(DATABASE_NAME);
or
context.deleteDatabase(path);
答案 3 :(得分:1)
对我来说,工作解决方案是:
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type IS 'table'" +
" AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
null
);
if(c.moveToFirst()){
do{
db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
}while(c.moveToNext());
}