如何在SQLite中删除所有表?
同样地,我想删除所有索引。
虽然没有DROP ALL TABLES命令,但可以使用以下一组命令。
注意:这些命令可能会损坏您的数据库,请确保备份。
PRAGMA writable_schema = 1;
delete from sqlite_master where type in ('table', 'index', 'trigger');
PRAGMA writable_schema = 0;
然后您希望使用
恢复已删除的空间VACUUM;
而且这是一个好的测试,以确保一切都正常
PRAGMA INTEGRITY_CHECK;
我认为你不能一次性删除所有表格,但你可以通过以下方式获取命令:
select 'drop table ' || name || ';' from sqlite_master
where type = 'table';
这将生成一个脚本,以便为您删除表。对于索引,只需将table替换为index即可。rm db/development.sqlite3
我在使用SQLite和Android时遇到了同样的问题,以下是我的解决方案:
List<String> tables = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String tableName = cursor.getString(1);
if (!tableName.equals("android_metadata") &&
!tableName.equals("sqlite_sequence"))
tables.add(tableName);
cursor.moveToNext();
}
cursor.close();
for(String tableName:tables) {
db.execSQL("DROP TABLE IF EXISTS " + tableName);
}
使用pysqlite:
tables = list(cur.execute("select name from sqlite_master where type is 'table'"))
cur.executescript(';'.join(["drop table if exists %s" %i for i in tables]))
除了删除表而不删除文件的其他答案所述,您还可以执行 delete from sqlite_sequence
来重置自增序列。
一旦您删除了所有表格(当表格消失时,索引也会消失),据我所知,在SQLite数据库中就没有剩余的内容了,尽管文件似乎不会缩小(根据我刚刚进行的快速测试)。因此,删除文件似乎是最快的方法 - 当您的应用程序尝试访问数据库文件时,它应该会被重新创建。
我在Android中遇到了这个问题,我编写了一个类似于it-west的方法。
因为我在我的表中使用了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();
}
}
我不能说这是最牢固或最便携的解决方案,但它适用于我的测试脚本:
.output /tmp/temp_drop_tables.sql
select 'drop table ' || name || ';' from sqlite_master where type = 'table';
.output stdout
.read /tmp/temp_drop_tables.sql
.system rm /tmp/temp_drop_tables.sql
如果要删除视图,请添加“view”关键字:
delete from sqlite_master where type in ('view', 'table', 'index', 'trigger');
android_metadata
表。下次打开数据库时,该表将被重新创建,但如果要立即重新创建它,可以将预写日志或外键约束翻转为与您配置的相反,然后再翻转回来。这将触发一个内部的reconfigure()
调用,该调用将编写出android_metadata
表。 - tophyr