很多次项目上线都会遗漏掉数据库的修改,因为本地开发好几个人做,开发环境都是在本地,项目是在云上跑的,总有人记不住自己本地修改了哪些表,导致每次上线完发现有问题,回过来查才发现是数据库忘记update了
需求:两个mysql数据库对比表结构,输出差异部分,用于上线前数据库修改
后端代码:
app.py
from flask import Flask, render_template, request
import mysql.connector
app = Flask(__name__)
# 配置MySQL连接信息
db1_config = {
'host': 'host1',
'user': 'user1',
'password': 'password1',
'database': 'database1',
'port': 'port1'
}
db2_config = {
'host': 'host2',
'user': 'user2',
'password': 'password2',
'database': 'database2',
'port': 'port2'
}
# 连接数据库并获取表结构信息
def get_table_structure(config):
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
table_structure = {
}
for table in tables:
cursor.execute(f"SHOW CREATE TABLE {
table}")
table_info = cursor.fetchone()
table_structure[table] = table_info[1]
cursor.close()
conn.close()
return table_structure
# 对比两个数据库的表结构差异
def compare_table_structure(db1_structure, db2_structure):
diff_result = {
}
for table, structure in db1_structure.items():
if table in db2_structure:
if structure != db2_structure[table]:
diff_result[table] = {
'db1_structure': structure,
'db2_structure': db2_structure[table]
}
else:
diff_result[table] = {
'db1_structure': structure,
'db2_structure': 'Table not exists in db2'
}
for table, structure in db2_structure.items():
if table not in db1_structure:
diff_result[table] = {
'db1_structure': 'Table not exists in db1',
'db2_structure': structure
}
return diff_result
@app.route('/')
def index():
return render_template