侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python 实现数据库更新脚本的生成方法

Python  /  管理员 发布于 7年前   164

我在工作的时候,在测试环境下使用的数据库跟生产环境的数据库不一致,当我们的测试环境下的数据库完成测试准备更新到生产环境上的数据库时候,需要准备更新脚本,真是一不小心没记下来就会忘了改了哪里,哪里添加了什么,这个真是非常让人头疼。因此我就试着用Python来实现自动的生成更新脚本,以免我这烂记性,记不住事。

主要操作如下:

1.在原先 basedao.py 中添加如下方法,这样旧能很方便的获取数据库的数据,为测试数据库和生产数据库做对比打下了基础。

def select_database_struts(self):    '''    查找当前连接配置中的数据库结构以字典集合    '''    sql = '''SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_TYPE, COLUMN_KEY, COLUMN_COMMENT        FROM information_schema.`COLUMNS`         WHERE TABLE_SCHEMA="%s" AND TABLE_NAME="{0}" '''%(self.__database)    struts = {}    for k in self.__primaryKey_dict.keys():      self.__cursor.execute(sql.format(k))      results = self.__cursor.fetchall()      struts[k] = {}      for result in results:        struts[k][result[0]] = {}        struts[k][result[0]]["COLUMN_NAME"] = result[0]        struts[k][result[0]]["IS_NULLABLE"] = result[1]        struts[k][result[0]]["COLUMN_TYPE"] = result[2]        struts[k][result[0]]["COLUMN_KEY"] = result[3]        struts[k][result[0]]["COLUMN_COMMENT"] = result[4]    return self.__config, struts

2.编写对比的Python脚本

'''数据库迁移脚本, 目前支持一下几种功能:1.生成旧数据库中没有的数据库表执行 SQL 脚本(支持是否带表数据),生成的 SQL 脚本在 temp 目录下(表名.sql)。2.生成添加列 SQL 脚本,生成的 SQL 脚本统一放在 temp 目录下的 depoyed.sql 中。3.生成修改列属性 SQL 脚本,生成的 SQL 脚本统一放在 temp 目录下的 depoyed.sql 中。4.生成删除列 SQL 脚本,生成的 SQL 脚本统一放在 temp 目录下的 depoyed.sql 中。'''import json, os, sysfrom basedao import BaseDaotemp_path = sys.path[0] + "/temp"if not os.path.exists(temp_path):  os.mkdir(temp_path)def main(old, new, has_data=False):  '''  @old 旧数据库(目标数据库)  @new 最新的数据库(源数据库)  @has_data 是否生成结构+数据的sql脚本   '''  clear_temp()  # 先清理 temp 目录  old_config, old_struts = old  new_config, new_struts = new  for new_table, new_fields in new_struts.items():    if old_struts.get(new_table) is None:      gc_sql(new_config["user"], new_config["password"], new_config["database"], new_table, has_data)    else:      cmp_table(old_struts[new_table], new_struts[new_table], new_table)def cmp_table(old, new, table):  '''  对比表结构生成 sql  '''  old_fields = old  new_fields = new  sql_add_column = "ALTER TABLE `{TABLE}` ADD COLUMN `{COLUMN_NAME}` {COLUMN_TYPE} COMMENT '{COLUMN_COMMENT}';\n"  sql_change_column = "ALTER TABLE `{TABLE}` CHANGE `{COLUMN_NAME}` `{COLUMN_NAME}` {COLUMN_TYPE} COMMENT '{COLUMN_COMMENT}';\n"  sql_del_column = "ALTER TABLE `{TABLE}` DROP {COLUMN_NAME};"  if old_fields != new_fields:    f = open(sys.path[0] + "/temp/deploy.sql", "a", encoding="utf8")    content = ""    for new_field, new_field_dict in new_fields.items():      old_filed_dict = old_fields.get(new_field)      if old_filed_dict is None:        # 生成添加列 sql        content += sql_add_column.format(TABLE=table, **new_field_dict)      else:        # 生成修改列 sql        if old_filed_dict != new_field_dict:          content += sql_change_column.format(TABLE=table, **new_field_dict)        pass    # 生成删除列 sql    for old_field, old_field_dict in old_fields.items():      if new_fields.get(old_field) is None:        content += sql_del_column.format(TABLE=table, COLUMN_NAME=old_field)f.write(content)    f.close()def gc_sql(user, pwd, db, table, has_data):  '''  生成 sql 文件  '''  if has_data:    sys_order = "mysqldump -u%s -p%s %s %s > %s/%s.sql"%(user, pwd, db, table, temp_path, table)  else:    sys_order = "mysqldump -u%s -p%s -d %s %s > %s/%s.sql"%(user, pwd, db, table, temp_path, table)  os.system(sys_order)def clear_temp():  '''  每次执行的时候调用这个,先清理下temp目录下面的旧文件  '''  if os.path.exists(temp_path):    files = os.listdir(temp_path)    for file in files:      f = os.path.join(temp_path, file)      if os.path.isfile(f):        os.remove(f)  print("临时文件目录清理完成")if __name__ == "__main__":  test1_config = {    "user" : "root",     "password" : "root",    "database" : "test1",   }  test2_config = {    "user" : "root",     "password" : "root",    "database" : "test2",   }    test1_dao = BaseDao(**test1_config)  test1_struts = test1_dao.select_database_struts()    test2_dao = BaseDao(**test2_config)  test2_struts = test2_dao.select_database_struts()  main(test2_struts, test1_struts)

目前只支持了4种SQL脚本的生成。

以上这篇Python 实现数据库更新脚本的生成方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    CentOS中升级Python版本的方法详解
    下一条:
    Python 实现数据库(SQL)更新脚本的生成方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客