在 pyodbc 中处理异常(无连接时)

Handling exception (when no connection) in pyodbc

我试图在连接到数据库时捕获异常并且没有连接,但我总是冻结在pyodbc.connect(connstr)。我尝试了 documentation 中的所有错误,只尝试了 "except Exception",但我看到我的程序在无法连接到数据库时冻结并且不检查 except 部分。 (冻结是由于我故意断开与数据库的连接,程序什么都不做(windows "no answer")直到我硬重置):

    import pyodbc
    connstr=('DRIVER={SQL Server Native Client 11.0};Server="server_ip";port=1433;Network Library=DBMSSOCN;Database="name";uid="uid";pwd="pwd";')
    try:
        print("I'm here - no problem")
        conn=pyodbc.connect(connstr)
        print("of course not here")
    except ...no_matter_what_I_write_here... :
        print("but never there too") 

假设您不是在线程上连接。因为信号在非主线程中不起作用。

import signal
from contextlib import contextmanager

 class TimeoutError(Exception): pass

 @contextmanager
 def time_limit(seconds):
     def signal_handler(signum, frame):
         raise TimeoutError("Time out")
     signal.signal(signal.SIGALRM, signal_handler)
     signal.alarm(seconds)
     try:
          yield
     finally:
          signal.alarm(0)


 try:
     with time_limit(10):
          conn=pyodbc.connect(connstr)     
 except TimeoutError as e:
        print "couldn't connect for long time"

太简单了(谢谢 Pynchia 的建议):

try:
    conn=pyodbc.connect(connstr, timeout=5)
except pyodbc.Error as err:
    print("Couldn't connect")