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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With