python 读取mysqlDB中指定的表名的DDL语句

发布时间 2023-09-07 15:38:57作者: 人间春风意

注意:

1. 此python文件不要起名为mysql,会跟import的包名重复,python mysql.py运行报错

2.如果需要带端口号,请加database后加上, port="3306"

环境:

python: 3.9.2 

Successfully installed mysql-connector-python-8.1.0 protobuf-4.21.12

 

1. 安装mysql-connector-python

pip install mysql-connector-python

2. 脚本内容:

import mysql.connector

cnx = mysql.connector.connect(
    host="127.0.0.1",
    user="xxx",
    password="xxx",
    database="xxxx"
)

# 创建游标对象
cursor = cnx.cursor()

# 要查询的表名列表
table_names = ["table1",
"table2",
"table3",
"table4"]

# 存储每个表的结果
table_results = {}

# 遍历表名列表,执行SHOW CREATE TABLE查询,并将结果存储到字典中
for table_name in table_names:
    query = f"SHOW CREATE TABLE {table_name}"
    cursor.execute(query)
    result = cursor.fetchone()
    table_results[table_name] = result[1]  # 获取第二个元素,即SHOW CREATE TABLE的结果

# 将结果串联起来,每个表的定义之间用分号分隔
concatenated_result = ";\n\n ".join(table_results.values())
print(concatenated_result)

# 关闭游标和连接
cursor.close()
cnx.close()