Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a DB connection timeout for a python/pyodbc/unixODBC/MS ODBC Driver 11 for SQL Server/Linux stack?

I've been unable to find a documented way to set a timeout for the initial connection that actually works. I'm not asking about a "query timeout", but rather a timeout on an initial connection attempt in the case that the DB server is completely down or unreachable, and there's no response at all. By default, such connections appear to timeout after 255 seconds - is there a way to set a shorter timeout?

Edit: for clarity, I should reiterate the stack here:

  • python
  • pyodbc
  • unixODBC (not iODBC)
  • MS ODBC Driver 11 for SQL Server (not FreeTDS)
  • Linux
like image 287
mikenerone Avatar asked Sep 12 '13 20:09

mikenerone


People also ask

How do I set ODBC connection timeout?

To specify a connection time-out, set the ConnectionTimeout property before calling Open. This is equivalent to setting the ODBC SQLSetConnectAttr SQL_ATTR_LOGIN_TIMOUT attribute.

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 ODBC timeout?

The ODBCTimeout property is an Integer value representing the number of seconds Microsoft Access waits. The default is 60 seconds.

What is the default connection timeout for SQL connection?

The default value is 15 seconds.


1 Answers

https://stackoverflow.com/a/12946908/1552953

This answer refers to being able to set a timeout on the connection:

Timeout

An optional integer query timeout, in seconds. 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.

If a query timeout occurs, the database should raise an OperationalError with SQLSTATE HYT00 or HYT01.

Note: This attribute only affects queries. To set the timeout for the actual connection process, use the timeout keyword of the pyodbc.connect function.

result = None
with pyodbc.connect('DRIVER={SQL Server};SERVER=mydb;DATABASE=solarwinds;Trusted_Connection=True', timeout=1) as cnxn:
    cursor = cnxn.cursor()
    result = cursor.execute(query).fetchall()

So using the above code it didn't timeout within 1 second, or at least it didn't return a result within 1 second. But it did return a result much faster than without a timeout set.

like image 85
James Burke Avatar answered Sep 28 '22 23:09

James Burke