I have some code that executes database queries, like so:
self.db_cursor = self.db_conn.cursor(buffered=False)
self.db_cursor.execute(query)
Now I want to add a timeout, so that long queries are killed. I can do this in MYSQL like this:
self.db_conn.reset_session(session_variables={'max_execution_time': 10})
(I deliberately set the timeout to be crazy short, for testing.)
How can I tell if a query timed out? I want to be able to report back to the user. There's no exception thrown, no warnings on the cursor, I can't find anything to check against.
I have some code that executes database queries, like so:
self.db_cursor = self.db_conn.cursor(buffered=False)
self.db_cursor.execute(query)
Now I want to add a timeout, so that long queries are killed. I can do this in MYSQL like this:
self.db_conn.reset_session(session_variables={'max_execution_time': 10})
(I deliberately set the timeout to be crazy short, for testing.)
How can I tell if a query timed out? I want to be able to report back to the user. There's no exception thrown, no warnings on the cursor, I can't find anything to check against.
Share Improve this question asked Mar 19 at 14:07 peckspecks 3401 gold badge2 silver badges10 bronze badges1 Answer
Reset to default 0Maybe with catching the Timeout Exception:
import mysql.connector
try:
self.db_conn.reset_session(session_variables={'max_execution_time': 10}) # Timeout in milliseconds
self.db_cursor = self.db_conn.cursor(buffered=False)
query = "SELECT SLEEP(5)" # Simulating a long query
self.db_cursor.execute(query)
results = self.db_cursor.fetchall() # Or fetchone()
print("Query executed successfully:", results)
except mysql.connector.errors.OperationalError as e:
if "Query execution was interrupted" in str(e):
print("Query timed out!")
else:
print("OperationalError:", e)
except mysql.connector.Error as e:
print("MySQL Error:", e)
finally:
self.db_cursor.close()