与 pyodbc 的通信 link 失败

Communication link failure with pyodbc

import pyodbc
import time
connection = pyodbc.connect(..............)
cursor = connection.cursor()
while True:
    time.sleep(1)
    cursor.execute(INSERT_QUERY)
    cursor.commit()

有效。但突然我得到一个例外 pyodbc.Error: ('08S01', '[08S01] [Microsoft][ODBC SQL Server Driver]Communication link failure (0) (SQLExecDirectW)')

为什么会这样?为什么 link 突然断开连接?我该如何处理该异常并重新连接?我该如何解决?

通过谷歌搜索错误代码,这意味着由于其他原因导致连接失败。

您可能想为这种情况添加 retry/reconnection 逻辑;大致是这样的。

import pyodbc
import time

connection = None
while True:
    time.sleep(1)
    if not connection:  # No connection yet? Connect.
        connection = pyodbc.connect("..............")
        cursor = connection.cursor()
    try:
        cursor.execute(INSERT_QUERY)
        cursor.commit()
    except pyodbc.Error as pe:
        print("Error:", pe)
        if pe.args[0] == "08S01":  # Communication error.
            # Nuke the connection and retry.
            try:
                connection.close()
            except:
                pass
            connection = None
            continue
        raise  # Re-raise any other exception