Home > Database > Mysql Tutorial > How to Enable Automatic Reconnection in MySQLdb for Persistent Database Interaction?

How to Enable Automatic Reconnection in MySQLdb for Persistent Database Interaction?

Linda Hamilton
Release: 2024-11-15 14:38:02
Original
912 people have browsed it

How to Enable Automatic Reconnection in MySQLdb for Persistent Database Interaction?

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template