1、获取表信息
首先,我们需要获取数据库中所有表的信息,包括表名、表注释等。
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='username', password='password', database='database_name')
cursor = conn.cursor()
# 查询所有表名及注释
cursor.execute("SELECT table_name, table_comment FROM information_schema.tables WHERE table_schema = 'your_database_name'")
tables_info = cursor.fetchall()
# 打印表信息
for table_info in tables_info:
print("表名:", table_info[0])
print("注释:", table_info[1])
print("-------------------")
# 关闭连接
cursor.close()
conn.close()2、获取字段信息
接下来,针对每个表,我们需要获取其字段信息,包括字段名、数据类型、字段长度、是否为主键、字段注释等。
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='username', password='password', database='database_name')
cursor = conn.cursor()
# 查询表字段信息
for table_info in tables_info:
table_name = table_info[0]
table_comment = table_info[1]
# 查询字段信息
cursor.execute(f"SHOW FULL COLUMNS FROM {table_name}")
columns_info = cursor.fetchall()
print("表名:", table_name)
print("注释:", table_comment)
print("字段信息:")
for column_info in columns_info:
print("字段名:", column_info[0])
print("数据类型:", column_info[1])
print("长度:", column_info[2])
print("是否为主键:", "是" if column_info[3] == "PRI" else "否")
print("注释:", column_info[8])
print("-------------------")
# 关闭连接
cursor.close()
conn.close()3、生成数据库字典
最后,将获取到的表信息和字段信息整理成数据库字典,并保存到文件中。
# 生成数据库字典
database_dictionary = {}
for table_info in tables_info:
table_name = table_info[0]
table_comment = table_info[1]
columns_info = []
# 查询字段信息
cursor.execute(f"SHOW FULL COLUMNS FROM {table_name}")
columns_info = cursor.fetchall()
# 整理字段信息
table_columns = []
for column_info in columns_info:
column_name = column_info[0]
data_type = column_info[1]
length = column_info[2]
is_primary_key = "是" if column_info[3] == "PRI" else "否"
column_comment = column_info[8]
table_columns.append({
"字段名": column_name,
"数据类型": data_type,
"长度": length,
"是否为主键": is_primary_key,
"注释": column_comment
})
# 添加表信息到数据库字典中
database_dictionary[table_name] = {
"表名": table_name,
"注释": table_comment,
"字段信息": table_columns
}
# 保存数据库字典到文件
import json
with open('database_dictionary.json', 'w') as file:
json.dump(database_dictionary, file, ensure_ascii=False, indent=4)
print("数据库字典已保存到 database_dictionary.json 文件中。")
# 关闭连接
cursor.close()
conn.close()通过以上步骤,我们完成了数据库字典的快速制作。现在,我们可以通过查看生成的数据库字典文件来了解数据库结构的详细信息。
