Python 数据库表结构同步

近日,某个QQ 群里的一个朋友提出一个问题,如何将一个DB 的表结构同步给另一个DB。
针对这个问题,我进行了思考与实践,具体的实现代码如下所示:

 1  
 2 # coding:utf-8
 3 import pymysql
 4  
 5 dbDict = {"test1":"l-beta.test1"}
 6 dbUser = "test"
 7 dbPassword = "123456"
 8  
 9 class DBUtils():
10     def __init__(self):
11         self.conn = pymysql.connect(dbDict['test1'], dbUser, dbPassword)
12         self.cursor = self.conn.cursor()
13  
14     def dbSelect(self, sql):
15         print("------------------------------------")
16         print(sql)
17         resultList = []
18         self.cursor.execute(sql)
19         result = self.cursor.fetchall()
20         columns = self.cursor.description
21         for val in result:
22             tempDict = {}
23             for cloNum in range(len(columns)):
24                 tempDict[str(columns[cloNum][0])] = val[cloNum]
25             resultList.append(tempDict)
26         print("---------------------打印查询结果----------------------")
27         print(resultList)
28         self.dbClose()
29         return resultList
30  
31     def dbExcute(self, sql):
32         print(sql)
33         self.cursor.execute(sql)
34         self.dbClose()
35  
36     def dbClose(self):
37         self.conn.commit()
38         self.cursor.close()
39         self.conn.close()
40  
41  
42 if __name__ == "__main__":
43     test = DBUtils()
44     result = test.dbSelect("select table_name from information_schema.tables where table_schema='testdb1'")
45     for dict1 in result:
46         test = DBUtils()
47         create_table_sql = "create table testdb.%s as select * from testdb1.%s" % (dict1['table_name'],dict1['table_name'])
48         print(create_table_sql)
49         test.dbExcute(create_table_sql)

示例代码操作简单,通俗易懂,所以没有过多的注释,如有疑问的小伙伴们,可在文章下方评论。

欢迎关注【无量测试之道】公众号,回复【领取资源】,
Python编程学习资源干货、
Python+Appium框架APP的UI自动化、
Python+Selenium框架Web的UI自动化、
Python+Unittest框架API自动化、

资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:

 添加关注,让我们一起共同成长!

原文地址:https://www.cnblogs.com/Wu13241454771/p/13613658.html