mysql的延迟函数_mysql延迟判断模板

使用自定义模板#!/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()函数定义在析构函数中,达到在对象使用完后,自动关闭连接的作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值