[英]how to drop all tables in sqlite3 using python?
i made a project which collects data from user and store it on different tables, the application has a delete function which the first option is to delete a specific table which is i already did and the second one is to delete all existing tables.我做了一个从用户收集数据并将其存储在不同表上的项目,该应用程序有一个删除 function,第一个选项是删除我已经做过的特定表,第二个是删除所有现有表。
How can i drop all tables inside my database?如何删除数据库中的所有表?
so this is my variables.所以这是我的变量。
conn = sqlite3.connect('main.db')
cursor = conn.execute("DROP TABLE")
cursor.close()
How can i drop all tables inside my database?如何删除数据库中的所有表?
According to sqlitetutorial.net根据sqlitetutorial.net
SQLite allows you to drop only one table at a time.
SQLite 允许您一次只删除一个表。 To remove multiple tables, you need to issue multiple
DROP TABLE
statements.要删除多个表,您需要发出多个
DROP TABLE
语句。
You can do it by querying all table names ( https://www.sqlite.org/faq.html#q7 )您可以通过查询所有表名 ( https://www.sqlite.org/faq.html#q7 )
Then you can use the result to delete the tables one by one然后你可以使用结果来一张一张地删除表
Here is the code, the function delete_all_tables
does that这是代码,function
delete_all_tables
就是这样做的
TABLE_PARAMETER = "{TABLE_PARAMETER}"
DROP_TABLE_SQL = f"DROP TABLE {TABLE_PARAMETER};"
GET_TABLES_SQL = "SELECT name FROM sqlite_schema WHERE type='table';"
def delete_all_tables(con):
tables = get_tables(con)
delete_tables(con, tables)
def get_tables(con):
cur = con.cursor()
cur.execute(GET_TABLES_SQL)
tables = cur.fetchall()
cur.close()
return tables
def delete_tables(con, tables):
cur = con.cursor()
for table, in tables:
sql = DROP_TABLE_SQL.replace(TABLE_PARAMETER, table)
cur.execute(sql)
cur.close()
SQLite3 code to issue multiple DROP TABLE statements based on TEMP_%
name wildcard: SQLite3 代码根据
TEMP_%
名称通配符发出多个 DROP TABLE 语句:
.output droptables.sql
SELECT "DROP TABLE """|| sqlite_master.name ||""";" FROM sqlite_master
WHERE type = "table" AND sqlite_master.name LIKE 'TEMP_%';
.read droptables.sql
Example result in.sql output file: .sql output 文件中的示例结果:
DROP TABLE "TEMP_table1";
DROP TABLE "TEMP_table2";
DROP TABLE "TEMP_table3";
...
Python3 to paste SQL into: Python3 将 SQL 粘贴到:
conn = sqlite3.connect(f"main.db")
conn.row_factory = sqlite3.Row
dbc = conn.cursor()
dbc.execute(
f"DROP TABLE 'TEMP_table1';"
)
conn.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.