

新闻资讯
技术学院同时修改多个数据库中同名表的技巧
你有大约 60 个数据库,每个数据库中有一张同名的表,需要对所有数据库中的这张表进行增删改查。如何实现此操作?
解决方案:
你可以使用以下步骤来实现:
1. 查看数据库中的所有表:
select * from information_schema.`tables` where table_name = 'undo_log';
2. 使用循环连接到每个数据库并操作表:
for i in range(60):
# 根据循环索引格式化数据库名称
db_name = 'db' + str(i)
# 连接到数据库
connection = mysql.connector.connect(
host='localhost',
user='root',
password='pass
word',
database=db_name
)
# 创建游标
cursor = connection.cursor()
# 执行操作(例如更新或删除)
cursor.execute("UPDATE undo_log SET message='Updated message' WHERE id=1")
# 提交更改
connection.commit()
# 关闭连接
cursor.close()
connection.close()注意: