对SQL Server的调用忽略pyodbc.connect timeout参数

Chr*_*est 8 python sql-server-2005 pyodbc

我在Linux上使用pyodbc和FreeTDS连接到SQL Server 2005.我注意到我的连接的超时参数没有被我的查询所尊重.

当我运行以下操作时,我希望在cursor.execute调用之后看到超时错误.

import pyodbc
import time

connString = 'SERVER=dbserver;PORT=1433;DATABASE=db;UID=dbuser;PWD=dbpwd;' + \
    'DRIVER=FreeTDS'
cnxn = pyodbc.connect(connString , timeout=3)

cursor = cnxn.cursor()

t1  = time.time()
cursor.execute("SELECT MAX(Qty) FROM big_table WHERE ID<10000005")
print cursor.fetchone()
t2 = time.time()
print t2-t1

cursor.execute("WAITFOR DELAY '00:00:30'")
print 'OK'
Run Code Online (Sandbox Code Playgroud)

相反,我得到了这个输出.指示第一个db查询占用7.5秒,第二个调用占用30秒而不会超时.

(808432.0, )
7.56196093559
OK
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来强制使用pyodbc和SQL Server查询超时?

Bry*_*yan 13

Connection.timeout变量赋值添加到代码中.默认为0(超时禁用),以秒为单位.

import pyodbc
import time

connString = 'SERVER=dbserver;PORT=1433;DATABASE=db;UID=dbuser;PWD=dbpwd;' + \
             'DRIVER=FreeTDS'
cnxn = pyodbc.connect(connString)
cnxn.timeout = 3
cursor = cnxn.cursor()

t1  = time.time()
cursor.execute("SELECT MAX(Qty) FROM big_table WHERE ID<10000005")
print cursor.fetchone()
t2 = time.time()
print t2-t1

cursor.execute("WAITFOR DELAY '00:00:30'")
print 'OK'
Run Code Online (Sandbox Code Playgroud)


iru*_*var 9

请参阅pyodbc连接,有两个单独的超时参数,Connection类上的一个变量(这会设置查询的超时)和一个pyodbc.connect的关键字参数(这个参数用于实际的连接过程).基于此,您将在代码中设置连接过程的超时,而不是查询.