[英]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?默认情况下,此类连接似乎在 255 秒后超时 - 有没有办法设置更短的超时?
Edit: for clarity, I should reiterate the stack here:编辑:为清楚起见,我应该在这里重申堆栈:
https://stackoverflow.com/a/12946908/1552953 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. 如果发生查询超时,则数据库应使用SQLSTATE HYT00或HYT01引发OperationalError。
Note: This attribute only affects queries. 注意:此属性仅影响查询。 To set the timeout for the actual connection process, use the timeout keyword of the pyodbc.connect function. 要设置实际连接过程的超时,请使用pyodbc.connect函数的timeout关键字。
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. 因此,使用上面的代码,它在1秒内没有超时,或者至少它在1秒内没有返回结果。 But it did return a result much faster than without a timeout set. 但它确实比没有超时设置更快地返回结果。
Solved here.在这里解决。 https://stackoverflow.com/a/35640876/2906290 https://stackoverflow.com/a/35640876/2906290
I've confirmed it works for pyodbc with MS SQL Server: https://docs.sqlalchemy.org/en/14/core/engines.html#use-the-connect-args-dictionary-parameter我已经确认它适用于带有 MS SQL Server 的 pyodbc: https ://docs.sqlalchemy.org/en/14/core/engines.html#use-the-connect-args-dictionary-parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.