Pyodbc + azure函数定时器通信链接错误/TCP Provider

问题描述 投票:0回答:1

我变得很随意

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

 
('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]Communication link failure (0) (SQLExecDirectW)')

尝试连接并执行简单的“select *”查询到另一个 SQL Server 时出现错误,如下所示:

query = "SELECT * FROM ProjectModule_Project"
cursor.execute(query)   
columns = [i[0] for i in cursor.description]
allRows = cursor.fetchall() 

令人困惑的是,这种情况只会在部署后的某个时候发生,这意味着如果我重新部署 Azure Function 并在此时触发它,它将无缝工作。

但是,如果让计时器自行运行一天左右,就会发生这种情况,并且所有后续手动调用也将产生相同的错误,直到重新部署为止。

如果有人可以提供帮助或为我指出一些方向,请感激不已。

python azure azure-functions pyodbc
1个回答
0
投票

由于功能应用程序长时间处于空闲状态,导致通信错误。在代码中使用 retries 只会再次创建新连接,下面是我的代码,无需重试即可使用:

import logging as ri_lg
import azure.functions as func
import pyodbc as rith

def main(req: func.HttpRequest) -> func.HttpResponse:
    ri_lg.info('Hello Rithwik Bojja, Execution Started')
    ri_usna = 'rithwik'
    r_passwd = 'test@123'
    ri_ser1 = 'rithwik.database.windows.net'
    db1 = 'rithwik'
    ri_th = f"Driver={{ODBC Driver 18 for SQL Server}};Server={ri_ser1};Database={db1};Uid={ri_usna};Pwd={r_passwd};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"
    with rith.connect(ri_th) as cho:
        with cho.cursor() as rit:
            rit.execute('SELECT TOP (1000) * FROM [dbo].[rith_cars];')
            var = rit.fetchone()
    print("Hello Rithwik Bojja the table is : ",var)
    ri_lg.info('Hello Rithwik Bojja, Azure Function is Executed')
    return func.HttpResponse(f"Hello Rithwik Bojja the table is: {var}", status_code=200)

输出:

enter image description here

欲了解更多信息,请参阅 SO-Thread1 SO-Thread2

您还可以使用如下的keepAlive,这可以保持连接处于活动状态

keep_alive = 100
ri_th = f"Driver={{ODBC Driver 18 for SQL Server}};Server={ri_ser1};Database={db1};Uid={ri_usna};Pwd={r_passwd};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;KeepAlive={keep_alive}"

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.