How python MySQLdb set read timeout read_timeout

In python, frequently used MySQLdboperations MySQL database.
In the implementation, MySQLdbnot the pure python, but encapsulates the MySQL C API library _mysql.

Whether MySQLdb support read_timeout, its manual did not mention this parameter. So, read_timeoutit really is available, the existence of doubt. It was also above the stack overflow asked the same question .

Next, we from MySQLdbthe source library MySQLdb-python github address begin, look at support read_timeout.

MySQLdbSource

Look at the code library HISTORYfile :

beta 4
======

Added support for the MySQL read_timeout option. Contributed by
Jean Schurger ([email protected]).

Added a workaround so that the MySQL character set utf8mb4 works with Python; utf8 is substituted
on the Python side.

Which has been clearly mentioned that the parameters have been read_timeoutprovided support.

The look, the underlying code is how to achieve _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

From the code, you can see, MySQL is supported from version 5.1.12 read_timeout.

MySQLdbIn the specific implementation, by
mysql_options()setting parameters MYSQL_OPT_READ_TIMEOUT, to achieve read out.

On MYSQL_OPT_READ_TIMEOUTand MYSQL_OPT_WRITE_TIMEOUTyou can refer to the official MySQL documentation
mysql_options () .

Let's look at MySQLdb-pythonthe read_timeouthow.

read_timeoutexample

In the following example, we set read_timeoutas 5s, sql statement is executed and more than 5s.
View the results of its execution.

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')

It can be seen when the sql statement is executed more than 5s, the connection is broken.
It has reached the desired effect.

reference

Operation Python MySQL database

MySQLdb-python installation

MySQLdb-python use the document

MySQLdb-python github address

MySQL C API

Guess you like

Origin www.cnblogs.com/lanyangsh/p/11259426.html