循环连接到 mysql

connect to mysql in a loop

我必须连接到 mysql 服务器并永久获取一些数据

所以我有两种方式

1)稍后连接mysql抓取数据

conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
while True:
  cursor.execute("statments")
  sqlData = cursor.fetchone()
  print(sqlData)
  sleep(0.5)

这工作正常,但如果脚本因 mysql 连接问题脚本崩溃

2) 在

中连接到 mysql
while True:
   try:
      conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
      cursor = conn.cursor(buffered=True)
      cursor.execute("statments")
      sqlData = cursor.fetchone()
      print(sqlData)
      cursor.close()
      conn.close()
      sleep(0.5)
   except:
      print("recoverable error..")

两种代码都运行良好,但我的问题是哪个更好?!

在这两种方法中,更好的方法是使用单个连接,但为每个语句创建一个新游标,因为创建新连接需要时间,但创建新游标很快。您可以将代码更新为:

conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
while True:
    try:
        cursor = conn.cursor(buffered=True)
        cursor.execute("statments")
        sqlData = cursor.fetchone()
        print(sqlData)
    except Exception: # Catch exception which will be raise in connection loss

        conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
        cursor = conn.cursor(buffered=True)

    finally:
        cursor.close()

conn.close()    # Close the connection

另请阅读 Defining Clean-up Actions 关于 try:finally 块的用法。