使用自定义模板#!/usr/bin/env python
#coding:utf-8
import MySQLdb
import torndb
sql_s = "show slave status"
sql_m = "show master status"
# 使用MySQLdb的连接
def db_conM(args):
# args = {'host':[mhost,shost],'user':user,'passwd':passwd,'db':db,'port':3306,'con_timeout':5}
# 有从库时,判断延迟,大于50则连接主库
if args['host'][1] != '' :
try:
sdb = MySQLdb.connect(host=args['host'][1],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=args['con_timeout'])
except Exception,e:
sdb = MySQLdb.connect(host=args['host'][0],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=10)
return sdb
cursor = sdb.cursor()
cursor.execute(sql_s)
seconds = int(cursor.fetchall()[0][32])
if seconds > 50 :
sdb = MySQLdb.connect(host=args['host'][0],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=10)
return sdb
# 没有从库时,直接连接主库
try:
sdb = MySQLdb.connect(host=args['host'][0],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=10)
except Exception,e:
print "Connect failed:%s"%e
return
# cursor = sdb.cursor()
return sdb
# 使用torndb的连接,判断方法类似
def get_conT(args):
# args = {'host':[mhost,shost],'user':user,'passwd':passwd,'db':db,'port':3306,'con_timeout':5}
if args['host'][1] != '':
try:
sdb = torndb.Connection("%s:%s"%(args['host'][0],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=args['con_timeout'])
except Exception,e:
sdb = torndb.Connection("%s:%s"%(args['host'][1],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=10)
return sdb
seconds = int(sdb.get(sql_s).Seconds_Behind_Master)
if seconds > 50 :
sdb = torndb.Connection("%s:%s"%(args['host'][1],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=10)
return sdb
try:
sdb = torndb.Connection("%s:%s"%(args['host'][1],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=10)
except Exception,e:
print "Connect failed:%s"%e
return
return sdb
将文件命名成db_help.py,后面的脚本直接引用,判断主从,切记在使用完连接后,记得关闭(sdb.close()的关闭)。
或者将以上两个函数用class进行封装,同时将sdb.close()函数定义在析构函数中,达到在对象使用完后,自动关闭连接的作用。