我正在从数据库的所有表中搜索批量删除。
DELETE FROM TABLE1,TABLE2,TABLE3; --(Is it possible)
像我们有批量插入一样
INSERT INTO TABLE (a,b,c) VALUES (1,2,3),(4,5,6),(7,8,9);
我不满意的代码就像这样。它能够做到这一点。
Delete from table1;
Delete from table2;
Delete from table3;
public void truncateDatabase() {
ArrayList<String> tables = new ArrayList<>();
Cursor cursor = Database.getInstance().getWritableDatabase().rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
tables.add(cursor.getString(0));
cursor.moveToNext();
}
}
cursor.close();
for (String table : tables) {
Database.getInstance().getWritableDatabase().execSQL("DELETE FROM " + table);
Database.getInstance().getWritableDatabase().execSQL("VACUUM");
}
}
答案 0 :(得分:1)
如documentation所示,单个DELETE语句适用于单个表。
执行多个DELETE语句没有错。
但是,您应该只执行一次VACUUM,并考虑使用事务:
SQLiteDatabase db = Database.getInstance().getWritableDatabase();
db.beginTransaction();
try {
for (String table : tables) {
db.execSQL("DELETE FROM " + table);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.execSQL("VACUUM");