Python 实现数据库(SQL)更新脚本的生成方法
作者:rcddup 发布时间:2024-01-16 21:01:18
标签:python,数据库,脚本
我在工作的时候,在测试环境下使用的数据库跟生产环境的数据库不一致,当我们的测试环境下的数据库完成测试准备更新到生产环境上的数据库时候,需要准备更新脚本,真是一不小心没记下来就会忘了改了哪里,哪里添加了什么,这个真是非常让人头疼。因此我就试着用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)更新脚本的生成方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
来源:http://www.cnblogs.com/rcddup/archive/2017/07/09/7141248.html


猜你喜欢
- Float(浮动)概念也许是CSS中最让人迷惑的一个概念吧。Float经常被错误理解,而且因为将上下文元素全部浮动导致的可读性、
- MooTools 1.2的整理排序类Sortables原文地址:30 Days of Mootools 1.2 Tutorials - Da
- 前几天,在所有数据库服务器部署了监控磁盘空间的存储过程和作业后(MS SQL 监控磁盘空间告警),今天突然收到了两封告警邮件,好吧,存储规划
- 线程间通信方法 1. 通信方法线程间使用全局变量进行通信 2. 共享
- 电脑环境:windows7 64位 python3.7问题:在PyCharm中,使用setting下
- # encoding: UTF-8import threadimport time# 一个用于在线程中执行的函数def func():&nb
- 写在前面:最近在做的person功能,由于后期系统中person人数较多,不利用查找person,故需求方将要求可以自己编辑每页显示的数目,
- microtime() 函数返回当前 Unix 时间戳的微秒数。用于检测程序执行时间的函数,也是PHP内置的时间函数之一,在PHP中可以用于
- 什么是上采样上采样,在深度学习框架中,可以简单的理解为任何可以让你的图像变成更高分辨率的技术。 最简单的方式是重采样和插值:将输入图片inp
- Python中的数据可视化matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地
- Python 循环Python 有两个原始的循环命令:while 循环for 循环while 循环如果使用 while 循环,只要条件为真,
- 有一个需求, 需要从数据库中导出两张表的数据到同一个excel中鉴于是临时的业务需求, 直接使用Navicat 进行查询并导出数据.数据涉及
- 1. 图片验证码1.1 工具类-utility.py将所有和图片验证码有关的方法放在类 ImageCodeimport randomimpo
- 1. 原理利用 PIL 库来获取图片并修改大小,利用灰度值转换公式把每一个像素的 RGB 值转为灰度值gray = int(0.2126*r
- 抽象工厂模式(Abstract Factory Pattern):属于创建型模式,它提供了一种创建对象的最佳方式。在抽象工厂模式中,接口是负
- 1 Tenacity描述今天 给大家介绍一个Python 重试库,Tenacity 这个库 是我 这些年 使用的一个非常好的库,几乎满足了我
- 如下所示:node2:/django/mysite/blog#cat views.py1,# -*- coding: utf-8 -*-fr
- Vue - 实现穿梭框功能,效果图如下所示:css.transfer{ display: flex;
- 1. 概念1.1 基本概念时间,对于我们来说很重要,什么时候做什么?什么时候发生什么?没有时间的概念,生活就乱了。在日常的运维当中,我们更关
- 前言Java 中最通用的日志模块莫过于 Log4j 了,在 python 中,也自带了 logging 模块,该模块的用法其实和 Log4j