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


Posted in Python onJuly 09, 2017

我在工作的时候,在测试环境下使用的数据库跟生产环境的数据库不一致,当我们的测试环境下的数据库完成测试准备更新到生产环境上的数据库时候,需要准备更新脚本,真是一不小心没记下来就会忘了改了哪里,哪里添加了什么,这个真是非常让人头疼。因此我就试着用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, sys
from basedao import BaseDao

temp_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 实现数据库(SQL)更新脚本的生成方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

Python 相关文章推荐
Python多线程实例教程
Sep 06 Python
python 3利用BeautifulSoup抓取div标签的方法示例
May 28 Python
Python字符串格式化的方法(两种)
Sep 19 Python
Python 记录日志的灵活性和可配置性介绍
Feb 27 Python
python中利用zfill方法自动给数字前面补0
Apr 10 Python
Python实现的计算器功能示例
Apr 26 Python
如何使用pyinstaller打包32位的exe程序
May 26 Python
Python面向对象之类和实例用法分析
Jun 08 Python
django formset实现数据表的批量操作的示例代码
Dec 06 Python
Python-jenkins模块获取jobs的执行状态操作
May 12 Python
tensorflow模型的save与restore,及checkpoint中读取变量方式
May 26 Python
python 偷懒技巧——使用 keyboard 录制键盘事件
Sep 21 Python
解决python文件字符串转列表时遇到空行的问题
Jul 09 #Python
python3 shelve模块的详解
Jul 08 #Python
Python基于scapy实现修改IP发送请求的方法示例
Jul 08 #Python
Python开发微信公众平台的方法详解【基于weixin-knife】
Jul 08 #Python
python 中random模块的常用方法总结
Jul 08 #Python
Python调用微信公众平台接口操作示例
Jul 08 #Python
HTML中使用python屏蔽一些基本功能的方法
Jul 07 #Python
You might like
php中使用__autoload()自动加载未定义类的实现代码
2013/02/06 PHP
深入PHP购物车模块功能分析(函数讲解,附源码)
2013/06/25 PHP
php猜单词游戏
2015/09/29 PHP
thinkPHP框架整合tcpdf插件操作示例
2018/08/07 PHP
js getElementsByTagName的简写方式
2010/06/27 Javascript
JQuery异步加载无限下拉框级联功能实现示例
2014/02/19 Javascript
js类型转换与引用类型详解(Boolean_Number_String)
2014/03/07 Javascript
简单谈谈jQuery(function(){})与(function(){})(jQuery)
2014/12/19 Javascript
JQuery插件ajaxfileupload.js异步上传文件实例
2015/05/19 Javascript
利用JavaScript判断浏览器类型及版本
2016/08/23 Javascript
JS常用知识点整理
2017/01/21 Javascript
JS 组件系列之Bootstrap Table 冻结列功能IE浏览器兼容性问题解决方案
2017/06/30 Javascript
Node.js中Bootstrap-table的两种分页的实现方法
2017/09/18 Javascript
Nodejs 和 Electron ubuntu下快速安装过程
2018/05/04 NodeJs
详解vue+webpack+express中间件接口使用
2018/07/17 Javascript
vue+iview 兼容IE11浏览器的实现方法
2019/01/07 Javascript
jQuery 查找元素操作实例小结
2019/10/02 jQuery
微信JSSDK实现打开摄像头拍照再将相片保存到服务器
2019/11/15 Javascript
python使用Matplotlib画饼图
2018/09/25 Python
详解python项目实战:模拟登陆CSDN
2019/04/04 Python
python写程序统计词频的方法
2019/07/29 Python
python线程定时器Timer实现原理解析
2019/11/30 Python
UGG英国官方网站:UGG UK
2018/02/08 全球购物
自我鉴定书面格式
2014/01/13 职场文书
2014年大学生自我评价
2014/01/19 职场文书
求职简历的自我评价
2014/01/31 职场文书
40岁生日感言
2014/02/15 职场文书
计算机大学生职业生涯规划书范文
2014/02/19 职场文书
函授本科个人自我鉴定
2014/03/25 职场文书
国旗下讲话演讲稿
2014/05/08 职场文书
法院反腐倡廉心得体会
2014/09/09 职场文书
2014年个人思想工作总结
2014/11/27 职场文书
先进个人推荐材料
2014/12/29 职场文书
2015年妇幼保健工作总结
2015/05/19 职场文书
JavaScript实现贪吃蛇游戏
2021/06/16 Javascript
深入讲解Vue中父子组件通信与事件触发
2022/03/22 Vue.js