使用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)
相关推荐
李李李勃谦6 分钟前
鸿蒙PCBI 报表工具:连接数据库与可视化报表生成
数据库·华为·交互·harmonyos
shaoming377612 分钟前
检查系统硬件配置是否满足PyCharm最低要求
android·spring boot·mysql
czlczl2002092543 分钟前
MAX()和MIN()优化
数据库·mysql·性能优化
开源情报局44 分钟前
79%的企业在用AI Agent,但只有2%规模化落地——问题出在哪?
人工智能·python
算法与双吉汉堡1 小时前
【Nanobot项目笔记】项目架构
python·ai·agent·智能体
knight_9___2 小时前
LLM工具调用面试篇6
人工智能·python·面试·职场和发展·llm·agent
用户3962691060032 小时前
asyncio + subprocess:Python异步调用外部命令踩坑实录
python
消失的旧时光-19432 小时前
SQL 第一篇:CRUD 实战,从 user 表开始写接口
数据库·sql·mysql
AI砖家2 小时前
Claude Code Superpowers 安装使用指南:让 AI 编程从“业余”走向“工程化”
前端·人工智能·python·ai编程·代码规范