我正在使用 http://www.ironpython.info/index.php/Accessing_SQL_Server 中的源代码使用 python 查询 MS SQL :
import clr
clr.AddReference('System.Data')
from System.Data import *
TheConnection = SqlClient.SqlConnection
("server=yourserver;database=News;uid=sa;password=password;timeout=0")
TheConnection.Open()
MyAction = SqlClient.SqlCommand("Select Headline from News", TheConnection)
MyReader = MyAction.ExecuteReader()
while MyReader.Read():
print MyReader[0]
MyReader.Close()
TheConnection.Close()
我刚刚添加了 timeout=0,但我仍然得到:
EnvironmentError: System.Data.SqlClient.SqlException (0x80131904): Timeout
expired. The timeout period elapsed prior to completion of the operation
or the server is not responding.
我用timeout=1000000 试过了,但还是报同样的错误。
如果我使用 MSSQL 客户端在同一台机器上运行相同的 SQL,那完全没问题。你知道如何避免这种超时异常吗?
请您参考如下方法:
尝试增加 SqlCommand 的 CommandTimeout 属性,如下所述: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx
连接字符串中的超时值只控制初始连接数据库的超时时间。如果您的 SQL 查询需要很长时间才能执行,那么这将无济于事,因此您需要改用 CommandTimeout。
