我先说下场景,昨天因为我们使用了Java工作流框架flowable,它自动生成了许多工作流相关的表,但是这些表都有外键关联,如果单纯的使用sql语句去一个一个的删除外键,那会非常麻烦,所以我写了一个Python脚本来进行批量删除。
前提是你要有个Python环境...
先安装mysql驱动依赖:
bash
pip install mysql-connector-python
因为代码非常简单,所以直接把代码粘出来,改下你mysql的连接信息,直接右键运行即可。
python
import mysql.connector
def delete_foreign_keys(host, port, user, password, database):
try:
# 连接到数据库
conn = mysql.connector.connect(
host=host,
port=port,
user=user,
password=password,
database=database
)
cursor = conn.cursor()
# 查询外键约束
cursor.execute("""
SELECT
CONSTRAINT_NAME,
TABLE_NAME
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE
UNIQUE_CONSTRAINT_SCHEMA = %s;
""", (database,))
foreign_keys = cursor.fetchall()
# 生成删除外键约束的 SQL 语句并执行
for fk in foreign_keys:
constraint_name, table_name = fk
cursor.execute(f"ALTER TABLE {table_name} DROP FOREIGN KEY {constraint_name};")
print(f"Deleted foreign key constraint {constraint_name} from table {table_name}")
conn.commit()
print("All foreign key constraints deleted successfully!")
except mysql.connector.Error as error:
print("Error while connecting to MySQL", error)
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
# 设置数据库连接参数
host = '127.0.0.1'
port = 3306 # MySQL 默认端口号
user = 'root'
password = 'root'
database = 'mydatabase'
# 调用函数删除外键约束
delete_foreign_keys(host, port, user, password, database)