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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法