简体   繁体   中英

Python mysql.connector timeout

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM