You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Azure Web App中Python使用pyodbc连接MS SQL出现[08S01](TCP Provider错误码0x68)的问题求助

Azure Web App中Python使用pyodbc连接MS SQL出现[08S01](TCP Provider错误码0x68)的问题求助

我有一个仅供自己测试技术知识的基础网站,会执行多个MS SQL查询操作。但最近遇到了一个头疼的问题:网站闲置一段时间后,就会弹出如下错误:

pyodbc.OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 18 for SQL Server]TCP Provider: Error code 0x68 (104) (SQLExecDirectW)')

我已经在网上搜过相关内容,看到一些解决思路提到这类错误是间歇性的,但我的情况更明确:只要重启Azure Web App后,白天持续刷新页面就不会出问题,只有闲置几个小时后才会触发连接断开的报错。

我尝试过写重新连接的逻辑,但没起到作用,我的代码如下:

odbc_str = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};Encrypt=yes;TrustServerCertificate=no;autocommit=True'
connection = pyodbc.connect(odbc_str, readonly=True)
cursor_conn = connection.cursor()

def get_results(seasonID):
    global connection, cursor_conn, odbc_str # Usage of global variables is not best practice
    if not connection:  # Because the website does not have lots of traffic, I suspect the connection is drop
        connection = pyodbc.connect(odbc_str, readonly=True)
        cursor_conn = connection.cursor()
    resultsQuery = "SELECT * FROM season_view"
    return cursor_conn.execute(resultsQuery).fetchall()

有没有大佬能给点解决建议?

备注:内容来源于stack exchange,提问作者AlbertoN

火山引擎 最新活动