使用pymysql 同步表结构

主要需求从一个 MySQL 数据库(源数据库)同步表结构到另一个 MySQL 数据库(目标数据库)。具体而言,它会从源数据库中获取每个表的创建 SQL 语句,并在目标数据库中执行这些语句,以创建相同的表结构。不依赖navicat可以用下面脚本很方便的进行同步

步骤分解

  1. 导入必要的库

    复制代码
    import mysql.connector

    这里导入了 mysql.connector,这是一个用于连接 MySQL 数据库的 Python 库。

  2. 数据库连接配置

    复制代码
    source_db_config = {
        'host': 'xxx',
        'port': 32562,
        'user': 'root',
        'password': 'xxx',
        'database': 'xxx'
    }
    
    target_db_config = {
        'host': 'xxx',
        'port': 30653,
        'user': 'root',
        'password': 'xxx',
        'database': 'xxx'
    }
    • 这里定义了两个字典 source_db_configtarget_db_config,分别包含源数据库和目标数据库的连接信息。
    • 包括主机地址、端口、用户名、密码和数据库名称。
  3. 获取表结构的函数

    复制代码
    def get_table_structure(cursor, table_name):
        cursor.execute(f"SHOW CREATE TABLE {table_name};")
        result = cursor.fetchone()
        return result[1]  # 获取创建表的 SQL 语句
    • 该函数接受一个数据库游标和表名作为参数。
    • 使用 SHOW CREATE TABLE SQL 语句获取指定表的创建 SQL 语句,并返回该语句。
  4. 同步表结构的函数

    复制代码
    def sync_table_structure(source_cursor, target_cursor, table_name):
        create_table_sql = get_table_structure(source_cursor, table_name)
        try:
            target_cursor.execute(f"DROP TABLE IF EXISTS {table_name};")  # 可选:先删除目标表
            target_cursor.execute(create_table_sql)
            print(f"表 {table_name} 结构已同步。")
        except mysql.connector.Error as err:
            print(f"表 {table_name} 同步失败: {err}")
    • 此函数用于从源数据库获取表结构并在目标数据库中创建相同的表。
    • 首先调用 get_table_structure 获取创建表的 SQL 语句。
    • 然后执行 DROP TABLE IF EXISTS 以删除目标数据库中已存在的同名表(这一操作是可选的)。
    • 最后,使用获取的 SQL 语句在目标数据库中创建表,并在控制台输出同步状态。
    • 如果在执行过程中出现错误,会捕获并打印错误信息。
  5. 主逻辑函数

    复制代码
    def main():
        # 连接源数据库
        source_conn = mysql.connector.connect(**source_db_config)
        source_cursor = source_conn.cursor()
    
        # 连接目标数据库
        target_conn = mysql.connector.connect(**target_db_config)
        target_cursor = target_conn.cursor()
    
        # 获取源数据库中的所有表
        source_cursor.execute("SHOW TABLES;")
        tables = source_cursor.fetchall()
    
        for (table_name,) in tables:
            sync_table_structure(source_cursor, target_cursor, table_name)
    
        # 关闭连接
        source_cursor.close()
        source_conn.close()
        target_cursor.close()
        target_conn.close()
    • main 函数是程序的入口点。
    • 首先,连接源和目标数据库,并创建相应的游标。
    • 使用 SHOW TABLES; 查询获取源数据库中的所有表名。
    • 对于每个表,调用 sync_table_structure 进行结构同步。
    • 最后,关闭所有游标和连接以释放资源。

完整脚本

复制代码
import mysql.connector

# MySQL 配置
source_db_config = {
    'host': '192.168.110.xx',
    'port': 32562,
    'user': 'root',
    'password': 'xxx',
    'database': 'xxx'
}

target_db_config = {
    'host': '192.168.110.xxx2',
    'port': 30653,
    'user': 'root',
    'password': 'xx',
    'database': 'xx'
}

def get_table_structure(cursor, table_name):
    cursor.execute(f"SHOW CREATE TABLE {table_name};")
    result = cursor.fetchone()
    return result[1]  # 获取创建表的 SQL 语句

def sync_table_structure(source_cursor, target_cursor, table_name):
    create_table_sql = get_table_structure(source_cursor, table_name)
    try:
        # 在目标数据库中执行创建表的 SQL
        target_cursor.execute(f"DROP TABLE IF EXISTS {table_name};")  # 可选:先删除目标表
        target_cursor.execute(create_table_sql)
        print(f"表 {table_name} 结构已同步。")
    except mysql.connector.Error as err:
        print(f"表 {table_name} 同步失败: {err}")

def main():
    # 连接源数据库
    source_conn = mysql.connector.connect(**source_db_config)
    source_cursor = source_conn.cursor()

    # 连接目标数据库
    target_conn = mysql.connector.connect(**target_db_config)
    target_cursor = target_conn.cursor()

    # 获取源数据库中的所有表
    source_cursor.execute("SHOW TABLES;")
    tables = source_cursor.fetchall()

    for (table_name,) in tables:
        sync_table_structure(source_cursor, target_cursor, table_name)

    # 关闭连接
    source_cursor.close()
    source_conn.close()
    target_cursor.close()
    target_conn.close()

if __name__ == "__main__":
    main()

后面就不赘述同步完检查了

相关推荐
IT龟苓膏5 小时前
Redis 数据类型底层原理:SDS、quicklist、intset、skiplist、Bitmap、HyperLogLog 一篇讲清
数据库·redis·skiplist
流星白龙6 小时前
【MySQL高阶】19.变更缓冲区,自适应哈希索引,日志缓冲区
数据库·windows·mysql
晴天¥6 小时前
Oracle中的监听配置与管理(动态、静态监听配置对比以及listener.ora和tnsnames.ora)
数据库·oracle
瀚高PG实验室7 小时前
python连接HGDB超时
数据库·瀚高数据库·highgo
闪电悠米8 小时前
黑马点评-Redisson-01_why_redisson
java·服务器·网络·数据库·缓存·wpf
Counter-Strike大牛8 小时前
SpringBoot2.7.10+MyBatisPlus实现MySQL+DM双数据库切换
数据库·mysql
dllxhcjla8 小时前
Redis
数据库·redis·缓存
睡不醒男孩0308238 小时前
数据库高可用运维实操指南:基于CLup的PostgreSQL生产环境自动化管理
运维·数据库·postgresql
神仙别闹8 小时前
基于Python + SQL server 实现(GUI)原神圣遗物管理与角色数值模拟系统
java·数据库·python
Crazy_eater9 小时前
Mysql(6)--基础查询
数据库·mysql