def get_table_structure(connection, cursor, database, table):
query = f"SHOW COLUMNS FROM {database}.{table}"
def generate_create_table(cursor, table_structure, database, table):
for column in table_structure:
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()
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):
for column_info in column_structure:
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):
f"ALTER TABLE `{database}`.`{table}` MODIFY COLUMN `{column_name}` {column_type} {is_nullable} {default_value} ;")
f"ALTER TABLE `{database}`.`{table}` ADD COLUMN `{column_name}` {column_type} {is_nullable} {default_value} ;")
def is_column_exists(cursor, database, table, column_name):
query = f"SHOW COLUMNS FROM `{database}`.`{table}` LIKE '{column_name}'"
return cursor.fetchone() is not None
if __name__ == "__main__":
db_a = pymysql.connect(host="127.0.0.1", port=3307, user="root", password="123456", database=dba)
db_b = pymysql.connect(host="127.0.0.1", port=3307, user="root", password="123456", database=dbb)
cursor_a.execute("SHOW TABLES")
database_a_tables = [table[0] for table in cursor_a.fetchall()]
cursor_b.execute("SHOW TABLES")
database_b_tables = [table[0] for table in cursor_b.fetchall()]
for table in database_a_tables:
if table not in database_b_tables:
table_structure = get_table_structure(db_a, cursor_a,dba, table)
create_table_sql = generate_create_table(cursor_a, table_structure, dbb, table)
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]
alter_column_sqls = generate_add_or_modify_column(db_b, cursor_b, dbb, table, column_diff)
for alter_column_sql in alter_column_sqls: