python 对比数据库,生成sql

python 复制代码
import pymysql


def get_table_structure(connection, cursor, database, table):
    # 获取表结构
    query = f"SHOW COLUMNS FROM {database}.{table}"
    cursor.execute(query)
    return cursor.fetchall()


def generate_create_table(cursor, table_structure, database, table):
    # 生成创建表的SQL语句,包含字段约束、默认值和主键信息
    columns = []
    for column in table_structure:
        column_name = column[0]
        column_type = column[1]
        is_nullable = "NOT NULL" if column[2] == "NO" else ""
        default_value = f"DEFAULT {column[4]}" if column[4] is not None else ""
        columns.append(f"`{column_name}` {column_type} {is_nullable} {default_value}")

    # 查找主键信息
    cursor.execute(f"SHOW KEYS FROM {table} WHERE Key_name = 'PRIMARY'")
    primary_key = cursor.fetchone()
    if primary_key:
        columns.append(f"PRIMARY KEY (`{primary_key[4]}`)")

    return f"CREATE TABLE `{database}`.`{table}` ({', '.join(columns)});"


def generate_add_or_modify_column(connection, cursor, database, table, column_structure):
    # 生成添加字段或修改字段的SQL语句
    alter_statements = []
    for column_info in column_structure:
        # column_name, column_type, is_nullable, default_value = column_info
        # default_clause = f"DEFAULT {default_value}" if default_value is not None else ""
        column_name = column_info[0]
        column_type = column_info[1]
        is_nullable = "NOT NULL" if column_info[2] == "NO" else ""
        default_value = f"DEFAULT  {column_info[4]}" if (column_info[4] is not None and column_info[4]) else "DEFAULT NULL"


        # 检查字段是否已经存在
        if is_column_exists(cursor, database, table, column_name):
            # 字段存在,生成修改字段的SQL语句
            alter_statements.append(
                f"ALTER TABLE `{database}`.`{table}` MODIFY COLUMN `{column_name}` {column_type} {is_nullable} {default_value} ;")
        else:
            # 字段不存在,生成添加字段的SQL语句
            alter_statements.append(
                f"ALTER TABLE `{database}`.`{table}` ADD COLUMN `{column_name}` {column_type} {is_nullable} {default_value} ;")

    return alter_statements


def is_column_exists(cursor, database, table, column_name):
    # 检查字段是否存在于目标表中
    query = f"SHOW COLUMNS FROM `{database}`.`{table}` LIKE '{column_name}'"
    cursor.execute(query)
    return cursor.fetchone() is not None


if __name__ == "__main__":

    dba ="test";
    dbb = "test1";
    # 连接数据库A
    db_a = pymysql.connect(host="127.0.0.1", port=3307, user="root", password="123456", database=dba)
    cursor_a = db_a.cursor()

    # 连接数据库B
    db_b = pymysql.connect(host="127.0.0.1", port=3307, user="root", password="123456", database=dbb)
    cursor_b = db_b.cursor()

    # 获取数据库A中的表
    cursor_a.execute("SHOW TABLES")
    database_a_tables = [table[0] for table in cursor_a.fetchall()]

    # 获取数据库B中的表
    cursor_b.execute("SHOW TABLES")
    database_b_tables = [table[0] for table in cursor_b.fetchall()]

    # 比较两个数据库的表结构并生成SQL语句
    for table in database_a_tables:
        if table not in database_b_tables:
            # 表在库B中缺失,生成创建表语句
            table_structure = get_table_structure(db_a, cursor_a,dba, table)
            create_table_sql = generate_create_table(cursor_a, table_structure, dbb, table)
            print(create_table_sql)
        else:
            # 表在库B中存在,比较字段
            columns_a = get_table_structure(db_a, cursor_a, dba, table)
            columns_b = get_table_structure(db_b, cursor_b,dbb, table)

            # 字段差异
            column_diff = [col for col in columns_a if col not in columns_b]

            # 生成添加字段或修改字段的SQL语句
            alter_column_sqls = generate_add_or_modify_column(db_b, cursor_b, dbb, table, column_diff)

            for alter_column_sql in alter_column_sqls:
                print(alter_column_sql)

    # 关闭数据库连接
    db_a.close()
    db_b.close()
相关推荐
MXsoft61810 分钟前
监控易监测对象及指标之:全面监控DB2_linux数据库
数据库·oracle
尘浮生17 分钟前
Java项目实战II基于Java+Spring Boot+MySQL的校园社团信息管理系统(源码+数据库+文档)
java·开发语言·数据库·spring boot·mysql·spring·maven
petaexpress31 分钟前
分布式云化数据库的优缺点分析
数据库·分布式
Lansonli36 分钟前
大数据Flink(一百二十):Flink SQL自定义函数(UDF)
大数据·sql·flink
失心疯_20231 小时前
Mysql_使用简介
数据库·sql·mysql·关系型数据库·ddl·dml·mysql教程
小威要向诸佬学习呀1 小时前
MySQL中的LIMIT与ORDER BY关键字详解
数据库·mysql
用生命在耍帅ㅤ1 小时前
mysql时间戳格式化yyyy-mm-dd
sql·mysql
Mero技术博客1 小时前
第二十节:学习Redis缓存数据库实现增删改查(自学Spring boot 3.x的第五天)
数据库·学习·缓存
为暗香来2 小时前
MySQL学习(视图总结)
数据库·学习·mysql
yzkkdhh2 小时前
【Windows 同时安装 MySQL5 和 MySQL8 - 详细图文教程】
windows·mysql·idea