最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

mysql - How do I detect a database timeout in python? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

Maybe 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()
发布评论

评论列表(0)

  1. 暂无评论