python MySQLdb 如何设置读超时read_timeout
在python中,经常用到 MySQLdb操作MySQL数据库。
在实现上,MySQLdb并不是纯python的,而是封装了MySQL C API库_mysql。
对于MySQLdb是否支持read_timeout,其使用手册中对这个参数只字未提。所以,read_timeout是否真的可用,是存在疑惑的。stack overflow上面也有人问到同样的问题。
接下来,我们从MySQLdb的源码库MySQLdb-python github地址开始,看下是否支持read_timeout。
MySQLdb的源码
先看下代码库中的HISTORY文件:
beta 4
======
Added support for the MySQL read_timeout option. Contributed by
Jean Schurger (jean@schurger.org).
Added a workaround so that the MySQL character set utf8mb4 works with Python; utf8 is substituted
on the Python side.
其中,已经明确提到,已经对参数read_timeout提供了支持。
再来看下,底层代码是如何实现的_mysql.c:
/* According to https://dev.mysql.com/doc/refman/5.1/en/mysql-options.html
The MYSQL_OPT_READ_TIMEOUT apear in the version 5.1.12 */
#if MYSQL_VERSION_ID > 50112
#define HAVE_MYSQL_OPT_TIMEOUTS 1
#endif
#ifdef HAVE_MYSQL_OPT_TIMEOUTS
if (read_timeout) {
unsigned int timeout = read_timeout;
mysql_options(&(self->connection), MYSQL_OPT_READ_TIMEOUT,
(char *)&timeout);
}
if (write_timeout) {
unsigned int timeout = write_timeout;
mysql_options(&(self->connection), MYSQL_OPT_WRITE_TIMEOUT,
(char *)&timeout);
}
#endif
从代码中,可以看到,MySQL从5.1.12版本开始支持read_timeout.
MySQLdb在具体实现上,通过
mysql_options()设置参数MYSQL_OPT_READ_TIMEOUT,来实现读超时。
关于MYSQL_OPT_READ_TIMEOUT和MYSQL_OPT_WRITE_TIMEOUT,可以参考MySQL官方文档说明
mysql_options()。
下面来看下MySQLdb-python中的read_timeout如何使用。
read_timeout例子
下面例子中,设置read_timeout为5s, 并使sql语句执行超过5s。
查看其执行结果。
import MySQLdb
from datetime import datetime
host = "127.0.0.1"
port = 3306
sql = "select sleep(10)"
user = "root"
passwd = "Aa123456"
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)
raise
ret = cursor.fetchone()
print("result:", ret)
cursor.close()
conn.close()
print("end")
output:
now: 2019-07-28 15:57:40.424942
now: 2019-07-28 15:57:45.425193
except: (2013, 'Lost connection to MySQL server during query')
Traceback (most recent call last):
File "read_timeout.py", line 19, in <module>
cursor.execute(sql)
File "/Users/lanyang/workspace/orange-service/.venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 198, in execute
res = self._query(query)
File "/Users/lanyang/workspace/orange-service/.venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 304, in _query
db.query(q)
File "/Users/lanyang/workspace/orange-service/.venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 217, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
可以看到,当sql语句执行超过5s后,连接被断开。
已经达到预期的效果。
参考
python MySQLdb 如何设置读超时read_timeout的更多相关文章
- 【python】Django设置SESSION超时时间没有生效?
按手册和网上的方法在settings.py中设置“SESSION_COOKIE_AGE” 和 “SESSION_EXPIRE_AT_BROWSER_CLOSE” 均不生效. 通过查看django的源代 ...
- HTTP请求的python实现(urlopen、headers处理、 Cookie处理、设置Timeout超时、 重定向、Proxy的设置)
python实现HTTP请求的三中方式:urllib2/urllib.httplib/urllib 以及Requests urllib2/urllib实现 urllib2和urllib是python两 ...
- iOS 设置connect超时
NSLock *theLock; [theLock lock]; int fd, error; struct sockaddr_in addr; ))<) { cout<<" ...
- python + seleinum +phantomjs 设置headers和proxy代理
python + seleinum +phantomjs 设置headers和proxy代理 最近因为工作需要使用selenium+phantomjs无头浏览器,其中遇到了一些坑,记录一下,尤 ...
- Python爬虫之设置selenium webdriver等待
Python爬虫之设置selenium webdriver等待 ajax技术出现使异步加载方式呈现数据的网站越来越多,当浏览器在加载页面时,页面上的元素可能并不是同时被加载完成,这给定位元素的定位增加 ...
- 关于python脚本头部设置#!/usr/bin/python
今天又是贼几把菜的一天0.0 读别人程序的时候看到在python文件头部设置签名,感觉贼几把酷,自己也试着在文件前段设置了一下. 设置还是蛮简单的,设置过程如图所示. 设置后如图所示: 当然你也可能看 ...
- python MySQLdb用法,python中cursor操作数据库(转)
数据库连接 连接数据库前,请先确认以下事项: 您已经创建了数据库 TESTDB. 在TESTDB数据库中您已经创建了表 EMPLOYEE EMPLOYEE表字段为 FIRST_NAME, LAST_N ...
- Python+Selenium自动化-设置等待三种等待方法
Python+Selenium自动化-设置等待三种等待方法 如果遇到使用ajax加载的网页,页面元素可能不是同时加载出来的,这个时候,就需要我们通过设置一个等待条件,等待页面元素加载完成,避免出现 ...
- C# 的tcp Socket设置自定义超时时间
简单的c# TCP通讯(TcpListener) C# 的TCP Socket (同步方式) C# 的TCP Socket (异步方式) C# 的tcp Socket设置自定义超时时间 C# TCP ...
随机推荐
- java文档注释规范(一)
https://blog.csdn.net/huangsiqian/article/details/82725214 Javadoc工具将从四种不同类型的“源”文件生成输出文档:Java语言类的源文件 ...
- 2019.12.9java公文流转系统
自己来写这个系统真是没有什么思路.就弄了个登陆界面,在数据库建了个表,其它的代码一直有错误,登陆不进去.
- 【HDU6635】Nonsense Time
题目大意:给定一个长度为 N 的序列,开始时所有的位置都不可用,每经过一个时间单位,都会有一个位置被激活.现给定激活顺序的序列,求每次激活之后全局的最长上升子序列的长度,保证数据随机. 题解: 引理: ...
- IC SPEC相关数据
---恢复内容开始--- 静态电流:静态电流是指没有信号输入时的电流,也就是器件本身在不受外部因素影响下的本身消耗电流. 纹波电压的害处: 1.容易在用设备中产生不期望的谐波,而谐波会产生较多的危害: ...
- dlerror和dlclose用法
dlclose() 1. 包含头文件 #include<dlfcn.h> 2. 函数定义 int dlclose(void *handle) dlclose用于关闭指定句柄的动态链接库, ...
- Acwing-98-分形之城(递推,数学)
链接: https://www.acwing.com/problem/content/description/100/ 题意: 城市的规划在城市建设中是个大问题. 不幸的是,很多城市在开始建设的时候并 ...
- Spring Boot干货系列:(十二)Spring Boot使用单元测试(转)
前言这次来介绍下Spring Boot中对单元测试的整合使用,本篇会通过以下4点来介绍,基本满足日常需求 Service层单元测试 Controller层单元测试 新断言assertThat使用 单元 ...
- entity framework delete table Error 11007:
udate model from database 数据库表删除时,会出现“Error 11007:”的异常,此时在.edmx文件中找到此表的实体发现还存在,删除它就没有这个错误 了.
- pyhton函数
函数编写文档 放在函数开头的字符串称为文档字符串(docstring),将作为函数的一部分存储起来 def square(x): 'Calculates the square of the numbe ...
- Qt 5 常用类及基本函数
//主要使用类#include <Qstring> #include <QMenu> #include <QMenuBar> #include <QToolB ...