1

我必须连接到 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)在while中连接到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..")

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

4

1 回答 1

0

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

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

另请阅读有关块使用的定义清理操作try:finally

于 2016-11-19T11:44:00.180 回答