Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyodbc.connect timeout argument is ignored for calls to SQL Server

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?

like image 752
ChrisGuest Avatar asked Oct 18 '12 00:10

ChrisGuest


People also ask

What is the default timeout for Pyodbc?

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.

How do I set SQL Server connection timeout?

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.

What is the default connection timeout for SQL Server?

The time (in seconds) to wait for a connection to open. The default value is 15 seconds.


2 Answers

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'
like image 175
Bryan Avatar answered Sep 19 '22 21:09

Bryan


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.

like image 44
iruvar Avatar answered Sep 20 '22 21:09

iruvar