2012-10-18 29 views
7

我在Linux上使用pyodbc与FreeTDS连接到SQL Server 2005.我注意到我的连接的超时参数没有被我的查询所尊重。Pyodbc.connect超时参数在调用SQL Server时被忽略

当我运行下面的代码时,我希望在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' 

而是我得到这个输出。指示第一个数据库查询超过7.5秒,第二个调用需要30秒而不会超时。

(808432.0,) 
7.56196093559 
OK 

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

回答

6

请参阅pyodbc connection,有两个单独的超时参数,Connection类中的一个变量(它设置查询的超时值)和一个关键字param给pyodbc.connect(以及这个用于实际连接过程)。基于此,您需要在代码中设置连接过程的超时时间,而不是查询。

10

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' 
+1

虽然我已经接受了cravori的优先答案,但您可以通过更详细的解释给出相同的解决方案。感谢那。 – ChrisGuest

+0

@ChrisGuest了解。 'timeout'变量对我来说也是新的信息,并且我不明白为了利用它而需要做些什么。希望这能帮助那些跑过它并像我一样密集的人:-) – Bryan