Ton*_*hew 16 database sqlite android
我做了很多研究,无法找到合适的方法来删除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());
}
Run Code Online (Sandbox Code Playgroud)
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();
}}
Run Code Online (Sandbox Code Playgroud)
Tim*_*sen 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);
}
Run Code Online (Sandbox Code Playgroud)
Tim Biegeleisen 的回答几乎对我有用,但是因为我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();
}
}
Run Code Online (Sandbox Code Playgroud)