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

作者:Wu_Candy 时间:2024-01-21 16:38:44 

近日,某个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)

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

来源:https://www.cnblogs.com/Wu13241454771/p/13613658.html

标签:python,数据库,表,结构同步
0
投稿

猜你喜欢

  • python+Django+apache的配置方法详解

    2021-02-18 06:39:06
  • mysql 5.7更改数据库的数据存储位置的解决方法

    2024-01-21 11:56:43
  • Python实现数值积分方式

    2022-01-23 14:00:37
  • perl AnyEvent简单介绍和入门知识

    2022-09-22 03:10:50
  • Pandas GroupBy对象 索引与迭代方法

    2022-12-08 17:32:12
  • 深入了解Python iter() 方法的用法

    2023-11-05 02:12:37
  • Vue路由切换页面不更新问题解决方案

    2024-04-28 10:53:21
  • Python浅析匿名函数lambda的用法

    2022-07-19 18:29:29
  • 实例:ASP与ACCESS链接

    2008-11-21 16:10:00
  • ASP下标越界错误的解决方法

    2008-10-19 17:39:00
  • 微信小程序实现电影App导航和轮播

    2024-04-18 09:49:32
  • Xml Http抓取数据时乱码问题解决

    2008-04-24 11:16:00
  • Python OpenCV对图像进行模糊处理详解流程

    2022-05-16 03:54:19
  • 浅谈python下含中文字符串正则表达式的编码问题

    2022-04-08 01:18:35
  • Python socket套接字实现C/S模式远程命令执行功能案例

    2021-11-27 13:22:01
  • javascript 用函数语句和表达式定义函数的区别详解

    2024-04-16 09:06:26
  • Scrapy爬虫实例讲解_校花网

    2023-03-02 14:46:39
  • 浅谈vue单一组件下动态修改数据时的全部重渲染

    2024-04-27 15:51:55
  • Python必须了解的35个关键词

    2023-05-20 07:37:33
  • JavaScript加密解密终级指南

    2008-01-03 12:25:00
  • asp之家 网络编程 m.aspxhome.com