您的位置:首页 > 编程语言 > Python开发

python 随便写的数据库差异化比较,并自动生成差异化脚本

2015-08-13 14:57 676 查看
<pre name="code" class="python">__author__ = 'ydm'
# coding=utf8
import pymysql
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class MysqlTableTool:

def __init__(self):
try:
target_conn = pymysql.connect(host='xx', port=9906, user='xx',
passwd='xx', db='xx', charset='utf8')
target_cur = target_conn.cursor(pymysql.cursors.DictCursor)

local_conn = pymysql.connect(host='xx', port=3306, user='xx',
passwd='xx', db='qupai', charset='utf8')
local_cur = local_conn.cursor(pymysql.cursors.DictCursor)
self.path = os.path.abspath(os.curdir)+"/table.sql"
self.target_cur = target_cur
self.local_cur = local_cur
except pymysql.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

def create_table(self, table_name):
"""
目标库少表时,导出本地库的表结构, 生成差异化脚本
:param table_name:
:return:
"""
self.local_cur.execute('show create table %s' % table_name)
os.system("echo '%s' >> %s" % (self.local_cur.fetchall()[0]['Create Table'], self.path))

def show_tables(self):
"""
返回一个目标库的表集合
:return:
"""
tables = list()
self.target_cur.execute('show tables')
for table in self.target_cur.fetchall():
tables.append(table['Tables_in_duanqu_v2'])
return tables

def desc_table(self, table):
"""
返回目标表的结构
:param table:
:return:
"""
table_desc = list()
self.target_cur.execute('desc %s' % table)
for desc in self.target_cur.fetchall():
table_desc.append(desc['Field'])
return table_desc

def alter_table(self, table, table_desc):
"""
产生字段更新脚本
:param table:
:param table_desc:
:return:
"""
type_null = 'NOT NULL'
type_default = ''

if table_desc['Null'] == 'YES':
type_null = 'NULL'

if table_desc['Default']:
type_default = 'Default '+table_desc['Default']

sql = 'alter table `%s` add column `%s` %s %s %s' % (table, table_desc['Field'], table_desc['Type'],
type_null, type_default)
os.system("echo '%s' >> %s" % (sql, self.path))

def diff_tables(self):
"""
本地库和目标库进行比较,并生成差异化脚本
:return:
"""
os.system("echo '' > %s" % self.path)
self.local_cur.execute('show tables')
target_tables = self.show_tables()
for table in self.local_cur.fetchall():
table = table['Tables_in_qupai']
if table in target_tables:
target_table_desc = self.desc_table(table)
self.local_cur.execute('desc %s' % table)
for table_desc in self.local_cur.fetchall():
if not table_desc['Field'] in target_table_desc:
self.alter_table(table, table_desc)
else:
self.create_table(table)

if __name__ == '__main__':
MysqlTableTool().diff_tables()

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python