python连接mysql

本文详细阐述了如何通过设置MySQL的timeout参数来优化数据库连接性能,减少连接断开带来的开销,确保程序稳定运行。
        try:
            self.db=MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.dbname,charset="utf8")
            self.db.autocommit(True)
            self.cursor = self.db.cursor()
            self.cursor.execute("SET NAMES utf8")
            self.cursor.execute("SET CHARACTER_SET_CLIENT=utf8")
            self.cursor.execute("SET CHARACTER_SET_RESULTS=utf8")
            self.cursor.execute("SET WAIT_TIMEOUT=100")
            self.cursor.execute("SET INTERACTIVE_TIMEOUT=100")
            print "-----------------------mysql connect to %s-----------------------" %(self.host)
            sys.stdout.flush()
        except MySQLdb.Error, e:
            print "re_connect Error %d: %s " % (e.args[0], e.args[1])
            sys.stdout.flush()


self.cursor.execute("SET WAIT_TIMEOUT=100")

self.cursor.execute("SET INTERACTIVE_TIMEOUT=100")

这两句设置使一直运行的程序不用频繁的连接断开mysql,增加mysql的开销

 

ps:mysql的三种timeout

  connect_timeout 在connect函数中设置

  The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake.

  interactive_timeout

  The number of seconds the server waits for activity on an interactive connection before closing it.

  wait_timeout

  The number of seconds the server waits for activity on a noninteractive connection before closing it.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值