使用Python实现批量删除MYSQL数据库的全部外键

我先说下场景,昨天因为我们使用了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)
相关推荐
二级小助手3 小时前
2026 问卷全自动填表指南:油猴(Tampermonkey)保姆级教程
脚本·油猴
徐同保3 小时前
python异步函数语法解析,async with ... as ...语法解析
数据库·python·oracle
是梦终空3 小时前
计算机毕业设计266—基于Springboot+Vue3的共享单车管理系统(源代码+数据库)
数据库·spring boot·vue·课程设计·计算机毕业设计·源代码·共享单车系统
a285283 小时前
nginx的重定向
大数据·数据库·nginx
m***06683 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
蒂法就是我3 小时前
mysql主键索引和其他索引区别在哪里?
数据库·mysql
eWidget4 小时前
数据可视化进阶:Seaborn 柱状图、散点图与相关性分析
数据库·python·信息可视化·kingbase·数据库平替用金仓·金仓数据库
X54先生(人文科技)4 小时前
20260211_AdviceForTraditionalProgrammers
数据库·人工智能·ai编程
清水白石0084 小时前
Python 柯里化完全指南:从函数式思想到工程实践
linux·服务器·python