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

mpr*_*hni 3 python exception pyodbc python-3.x

我试图在连接到数据库并且没有连接时捕获异常,但我总是冻结在 pyodbc.connect(connstr) 处。我尝试了文档中的所有错误,只尝试了“例外”,但我看到我的程序在无法连接到数据库时冻结,并且不检查“例外”部分。(冻结是由于我故意与数据库断开连接而导致的,程序在硬重置之前什么也不执行(Windows“无应答”):

    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") 
Run Code Online (Sandbox Code Playgroud)

mpr*_*hni 7

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

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