首页 > 解决方案 > 使用 pyodbc 管理数据库轮询连接的最佳实践?

问题描述

我需要每 10 秒从 Python 应用程序在 Azure SQL 托管实例上运行一个存储过程。特定的调用cursor.execute()发生在一个threading.Thread像这样扩展的类中:

class Parser(threading.Thread):
    def __init__(self, name, event, interface, config):
        threading.Thread.__init__(self)
        self.name = name
        self.stopped = event
        self.interface = interface
        self.config = config
        self.connection_string = config['connection_string']
        self.cnxn = pyodbc.connect(self.connection_string)        

    def run(self):
        
        while not self.stopped.wait(10):
                
            try:
                cursor = self.cnxn.cursor()
                cursor.execute("exec dbo.myStoredProcedure")
            except Exception as e:
                logging.error(e)

我当前的挑战是上述线程无法从网络连接中断中正常恢复。我的目标是让线程继续运行并每 10 秒重新尝试一次,直到连接恢复,然后正常恢复。

在调试时我发现即使在连接恢复后, pyodbc.connect() 仍然失败并出现 ODBC 错误08S01 Communication link failure

我查看了这篇文章中提出的解决方案,但没有看到如何将该解决方案应用于连续轮询架构。

标签: odbcpython-multithreadingpyodbcazure-sql-managed-instance

解决方案


推荐阅读