您的位置:首页 > 数据库

比较数据库的表,字段是否一致,找出差异的表、字段

2017-03-26 11:38 274 查看
有时候测试环境跟正式环境,有一个表没创建,或者某个表有字段没创建,通过以下代码可以实现找出差异的表,字段。

conf记录的是数据库的连接用户名密码等信息。

还有改进的空间,例如 异常判断、linux环境执行时,支持正式环境 和哪个测试环境比对。有时不止一个测试库。、优化下冗余代码,代码可以更简洁一些。

#coding=utf-8
#/usr/bin/python
import conf
import MySQLdb
def get_data(env,sql):
if env == "test":
conn = MySQLdb.connect(conf.test_dbhost,conf.test_user,conf.test_passd,conf.dbname,charset="utf8")
else:
conn = MySQLdb.connect(conf.online_dbhost,conf.online_user,conf.online_passd,conf.dbname,charset="utf8")
cur = conn.cursor()
cur.execute(sql)
results = cur.fetchall() # 搜取所有结果
cur.close()
conn.close()
return results

def to_list(result):#把返回的嵌套元组转换为列表
r_list = []
for t in result:
r_list.append(t[0])
return r_list
def comp(L1,L2):#L1里有,但是L2没有
ret = [i for i in L1 if i not in L2]
return ret
def both_list(L1,L2):
both = [i for i in L1 if i in L2]
return both
def result(test,online):
test_have = comp(test,online)
online_have = comp(online,test)
if len(test_have)+len(online_have) != 0:
print "test环境有",test_have
print "online环境有",online_have
if __name__ =="__main__":
test_table_list = to_list(get_data('test',"show tables"))
online_table_list = to_list(get_data('online',"show tables"))
both_have_t = both_list(test_table_list,online_table_list)
result(test_table_list,online_table_list)#调用比较结果函数
print "开始比较共有表的字段"
for i in range(0,len(both_have_t)):
field_sql = "SELECT column_name FROM information_schema.columns WHERE Table_name= '%s'" %both_have_t[i]
test_field = to_list(get_data("test",field_sql))
online_field = to_list(get_data("online",field_sql))
print i+1,both_have_t[i]
result(test_field,online_field)
print "done"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: