与pyodbc通信链路失败

问题描述 投票:0回答:2
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)')

这是为什么?为什么链接突然断开?我该如何处理该异常并重新连接? 我该如何解决这个问题?

python pyodbc
2个回答
5
投票

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

您可能想为这种情况添加重试/重新连接逻辑;粗略地像这样。

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

-1
投票

苹果底毛皮牛仔靴

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.