我正在尝试在连接到数据库时捕获异常但没有连接,但我总是在pyodbc.connect(connstr)冻结。我尝试了来自documentation的所有错误,尝试了“除了异常”但我看到我的程序只是在无法连接数据库时冻结而且不检查除了部分。 (冻结是由于我故意断开数据库并且程序无效(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")
答案 0 :(得分:1)
这太简单了(谢谢Pynchia的建议):
try:
conn=pyodbc.connect(connstr, timeout=5)
except pyodbc.Error as err:
print("Couldn't connect")
答案 1 :(得分:0)
假设你没有在线程上连接。 Coz信号不适用于非主线程。
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"