在Python中,使用mysql-connector-python
库连接MySQL时,可以通过设置auto_reconnect
参数来实现自动重连。首先,确保已经安装了mysql-connector-python
库:
pip install mysql-connector-python
然后,在创建连接时设置auto_reconnect=True
:
import mysql.connector
from mysql.connector import Error
def create_connection():
try:
connection = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database",
auto_reconnect=True # 设置自动重连
)
return connection
except Error as e:
print(f"Error connecting to MySQL: {e}")
return None
def main():
connection = create_connection()
if connection:
print("Connection to MySQL was successful!")
# 在这里执行你的查询和操作
connection.close()
else:
print("Failed to connect to MySQL.")
if __name__ == "__main__":
main()
当设置auto_reconnect=True
时,如果连接断开或丢失,库会尝试自动重新连接。请注意,这种方法并不能保证100%的重连成功,因为网络问题、服务器故障等原因可能导致重连失败。在这种情况下,你需要根据实际情况调整重连策略,例如设置最大重连次数、重连间隔等。