Enabling MySQL Client Automatic Reconnection with MySQLdb
In Python, MySQLdb offers a convenient way to connect to MySQL databases. However, maintaining persistent connections can encounter issues, such as connection drops.
Question: How can we enable automatic reconnection in MySQLdb?
Solution: Despite the existence of a PHP method to handle this scenario, MySQLdb lacks a similar direct approach. However, employing a custom function can provide a solution.
The following code snippet demonstrates如何achieve automatic reconnection:
import MySQLdb class DB: conn = None def connect(self): self.conn = MySQLdb.connect() def query(self, sql): try: cursor = self.conn.cursor() cursor.execute(sql) except (AttributeError, MySQLdb.OperationalError): self.connect() cursor = self.conn.cursor() cursor.execute(sql) return cursor db = DB() sql = "SELECT * FROM foo" cur = db.query(sql) # Simulate a connection timeout with a delay time.sleep(600) cur = db.query(sql) # Connection still active
In this example, the query method attempts to execute queries. If a connection error occurs, it reconnects and retries the query. This mechanism ensures persistent database interaction despite intermittent connection drops.
The above is the detailed content of How to Enable Automatic Reconnection in MySQLdb for Persistent Database Interaction?. For more information, please follow other related articles on the PHP Chinese website!