背景:当mysql读取数据时,数据表大,读取无效数据或数据不存在时,程序长时间浪费,需要数据库需要设置读写超时。
调研:
mysqldb代码库:https://github.com/farcepest/MySQLdb1
中https://github.com/farcepest/MySQLdb1/blob/master/_mysql.c文件
MySQL从5.1.12版本开始支持read_timeout
查看history文件中https://github.com/farcepest/MySQLdb1/blob/master/HISTORY
可以看到mysqldb 1.2.4版本以后支持设置读超时。
测试代码
import MySQLdb
from datetime import datetime
host = "127.0.0.1"
port = 8789
sql = "select sleep(10)"
user = "xxx"
passwd = "xxx"
conn = MySQLdb.connect(host=host, port=port, user=user,passwd=passwd, connect_timeout=2, read_timeout=5, charset="utf8")
cursor = conn.cursor()
print("now:", datetime.now())
try:
cursor.execute(sql)
except Exception as e:
print("now:", datetime.now())
print("except:", e)
ret = cursor.fetchone()
print("result:", ret)
cursor.close()
conn.close()
print("end")
运行失败:
查看mysqldb版本发现为1.2.3低于默认版本,更新mysqldb即可成功