简体   繁体   English

从所有表中删除条目

[英]Removing entries from all tables

I'm writing a python script that would reset the database to an initial state (some hardcoded entries in every table). 我正在编写一个python脚本,它将数据库重置为初始状态(每个表中都有一些硬编码的条目)。 The db consists of multiple tables with primary and foreign keys. 该数据库由具有主键和外键的多个表组成。

Every time I would run the script, it should remove all the old entries in all of the tables, reset the primary key counter and insert the sample entries. 每次我运行脚本时,它都应该删除所有表中的所有旧条目,重置主键计数器并插入示例条目。

Currently I am trying to achieve this like this: 目前,我正在尝试实现以下目标:

# Delete all the entries from the tables 
cursor.execute("DELETE FROM table1")  
cursor.execute("DELETE FROM table2")  
cursor.execute("DELETE FROM table3")

# Reset the primary key counter and insert sample entries
cursor.execute("ALTER TABLE table1 AUTO_INCREMENT = 1") 
cursor.execute("INSERT INTO table1(username, password) VALUES('user01', '123')")

cursor.execute("ALTER TABLE table2 AUTO_INCREMENT = 1") 
cursor.execute("INSERT INTO table2(column1, column2) VALUES('column1_data', 'column2_data')")

This isn't working due to the presence of foreign keys in some tables (it won't let me delete them). 由于某些表中存在外键,因此无法正常工作(不允许我删除外键)。

I generate the tables using a models.py script (I also use Django), so I thought I could solve this the following way: 我使用models.py脚本(也使用Django)生成表,因此我认为可以通过以下方式解决此问题:

  1. remove the database programatically and create a new one with the same name 以编程方式删除数据库并创建一个具有相同名称的新数据库
  2. call the models.py script to generate empty tables in the db 调用models.py脚本在数据库中生成空表
  3. insert sample data using the script I wrote 使用我编写的脚本插入示例数据

Is this a good solution or am I overlooking something? 这是一个好的解决方案还是我忽略了什么?

I use scripts monthly to purge a transaction table, after archiving the contents. 归档内容后,我每月使用脚本清除交易表。

Try using the 'truncate' command, ie. 尝试使用“ truncate”命令,即。

truncate table [tablename]; 截断表[tablename];

It resets the counter (auto-increment) for primary key, automatically. 它将自动重置主键的计数器(自动递增)。 Then use your insert statements to populate base info. 然后使用您的插入语句来填充基本信息。

Also, this preserves all of the table base settings (keys,indexes,.). 此外,这将保留所有表基础设置(键,索引等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM