脚本专栏 
首页 > 脚本专栏 > 浏览文章

Python 如何实现数据库表结构同步

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

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

# coding:utf-8
import pymysql

dbDict = {"test1":"l-beta.test1"}
dbUser = "test"
dbPassword = "123456"

class DBUtils():
  def __init__(self):
    self.conn = pymysql.connect(dbDict['test1'], dbUser, dbPassword)
    self.cursor = self.conn.cursor()

  def dbSelect(self, sql):
    print("------------------------------------")
    print(sql)
    resultList = []
    self.cursor.execute(sql)
    result = self.cursor.fetchall()
    columns = self.cursor.description
    for val in result:
      tempDict = {}
      for cloNum in range(len(columns)):
        tempDict[str(columns[cloNum][0])] = val[cloNum]
      resultList.append(tempDict)
    print("---------------------打印查询结果----------------------")
    print(resultList)
    self.dbClose()
    return resultList

  def dbExcute(self, sql):
    print(sql)
    self.cursor.execute(sql)
    self.dbClose()

  def dbClose(self):
    self.conn.commit()
    self.cursor.close()
    self.conn.close()


if __name__ == "__main__":
  test = DBUtils()
  result = test.dbSelect("select table_name from information_schema.tables where table_schema='testdb1'")
  for dict1 in result:
    test = DBUtils()
    create_table_sql = "create table testdb.%s as select * from testdb1.%s" % (dict1['table_name'],dict1['table_name'])
    print(create_table_sql)
    test.dbExcute(create_table_sql)

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

以上就是Python 如何实现数据库表结构同步的详细内容,更多关于Python 数据库表结构同步的资料请关注其它相关文章!

上一篇:Python 字典一个键对应多个值的方法
下一篇:python 获取字典特定值对应的键的实现
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网