Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mysql.connector timeout

Tags:

python

mysql

Here's a simple connection to a MySQL database using the mysql.connector module.

db = mysql.connector.connect(
    host=DB_SERVER,
    port=DB_PORT,
    user=DB_UNAME,
    passwd=DB_PASSWORD,
    db=DB_NAME)
db.connect()
mysqlCursor.execute(query)

I want to control two different timeouts. First, I want it to spend no longer than five seconds on the .connect() function. I've got that figured out. Second, I want it to spend no longer than one second on the .execute() function. How can I do that?

I'm the database administrator, so I can do something on that end if I need to. I'd prefer only to change the timeout for one particular MySQL user, though, and not for everyone, which is why I'm starting from the Python side.

Here's what I've found so far:

The documentation for mysql.connecter lists several timeout parameters. Connect-timeout will set the timeout for the initial connection, but as far as I can tell, it won't set a query timeout. Interactive-timeout will cause it to timeout if there's no activity, but I don't think that means it will timeout if the query takes too long to execute.

connect-timeout=seconds Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server. (timeout has been replaced by connect-timeout, but timeout is still supported in MySQL 5.0 for backward compatibility.)

interactive-timeout=seconds Permit seconds of inactivity before closing the connection. The client's session wait_timeout variable is set to the value of the session interactive_timeout variable.

like image 345
Qaz Avatar asked Jun 20 '14 12:06

Qaz


People also ask

How do I keep MySQL connection alive in Python?

execute(...) . By doing this, the application uses 1 connection. The other way is to create connection every time I need to execute a transaction. Approach 1, prevents the application from creating and deleting connections over and over but it will face "mysql gone away" problem if it stays ideal.


1 Answers

As of MySQL 5.7.8 a maximum execution time for just SELECT statements can be set per session. Set this immediately after connecting:

db = mysql.connector.connect(...)
cursor = db.cursor()
# Limit SELECTs to 1 second
cursor.execute("SET SESSION MAX_EXECUTION_TIME=1000")
like image 124
Matt S Avatar answered Sep 30 '22 22:09

Matt S