删除所有表格命令

什么命令删除SQLite中的所有表?

同样,我想放弃所有索引。

我不认为你可以在一个命中中删除所有的表,但你可以做下面的命令:

select 'drop table ' || name || ';' from sqlite_master where type = 'table'; 

这个输出是一个脚本,会为你放下表格。 对于索引,只需用索引replace表。

您可以使用where部分中的其他子句来限制select哪些表或索引(例如,以“pax_”开头的and name glob 'pax_*'为“ and name glob 'pax_*' ”)。

您可以将这个脚本的创build与运行在一个简单的bash(或cmd.exe)脚本中,所以只有一个命令可以运行。

如果您不关心数据库中的任何信息,我认为您可以从硬盘上删除存储的文件 – 这可能会更快。 我从来没有testing过,但我不明白为什么它不会工作。

虽然确实没有DROP ALL TABLES命令,但您可以使用以下一组命令。

注意:这些命令有可能损坏您的数据库,因此请确保您有备份

 PRAGMA writable_schema = 1; delete from sqlite_master where type in ('table', 'index', 'trigger'); PRAGMA writable_schema = 0; 

然后你想要恢复已删除的空间

 VACUUM; 

和一个很好的testing,以确保一切正常

 PRAGMA INTEGRITY_CHECK; 
 rm db/development.sqlite3 

我有与SQLite和Android相同的问题。 这是我的解决scheme:

 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); } 

我想添加到其他答案涉及到删除表,而不是删除文件,你也可以执行delete from sqlite_sequence重置自动递增序列。

一旦你删除了所有的表(并且索引将在表中消失的时候),那么就我所知,SQLite数据库中没有任何东西留下,虽然这个文件看起来并没有缩小(从我刚刚做的一个快速testing)。

所以删除文件似乎是最快的 – 它应该只是当你的应用程序试图访问数据库文件时重新创build。

使用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])) 

我在android中有这个问题,我写了一个类似于西方的方法。

因为我在表中使用了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(); } }