在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%的重連成功,因為網絡問題、服務器故障等原因可能導致重連失敗。在這種情況下,你需要根據實際情況調整重連策略,例如設置最大重連次數、重連間隔等。