使用pyodbc管理数据库轮询连接的最佳做法?

问题描述

我需要从Python应用程序每10秒钟在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秒重新尝试一次,直到恢复连接,然后再进行正常恢复。

  • 此处的最佳做法是在while循环的每一遍中删除并重新创建连接吗?
  • 我应该在连接字符串中使用ConnectRetryCount还是ConnectRetryInterval

在调试过程中,我发现即使恢复了连接,pyodbc.connect()仍然会失败,并显示ODBC错误08S01 Communication link failure

我已经看过this post中提出的解决方案,但是没有看到如何将该解决方案应用于连续轮询架构。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)