I am using pyodbc on Linux with FreeTDS to connect to SQL Server 2005. I have noticed that the timeout argument to my connection is not being honoured by my queries.
When I run the following I would expect to see timeout errors after both cursor.execute calls.
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'
Instead I get this output. Indicating that the first db query is taking over 7.5 seconds and the second call is taking 30 seconds without throwing a timeout.
(808432.0, )
7.56196093559
OK
Is there a better way to force a query timeout using pyodbc and SQL Server?
Use zero, the default, to disable. The timeout is applied to all cursors created by the connection, so it cannot be changed for a given connection.
Using SQL Server Management StudioIn Object Explorer, right-click a server and select Properties. Click the Connections node. Under Remote server connections, in the Remote query timeout box, type or select a value from 0 through 2,147,483,647 to set the maximum number seconds for SQL Server to wait before timing out.
The time (in seconds) to wait for a connection to open. The default value is 15 seconds.
Add Connection.timeout
variable assignment to your code. Defaults to 0
(timeout disabled), expected in seconds.
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'
Refer pyodbc connection, there are two separate timeout parameters, a variable on the Connection class (this sets the timeout for queries) and a keyword param to pyodbc.connect (and this one for the actual connection process). Based on this you are setting the timeout for the connection process in your code and not for queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With