SQL Server的超时设置

我正在使用VSTS 2008 + ADO.Net + C#+。Net 3.5 + SQL Server 2008.我在客户端使用ADO.Net连接到数据库服务器以执行存储过程,然后从存储过程返回结果。

这是我的代码。 我有两个关于超时的问题,

  1. 如果我没有明确设置任何超时相关设置,对于与数据库服务器的连接,是否有任何超时设置(例如,如果在一段默认时间内无法连接到数据库服务器,会有一些超时exception?)?

  2. 如果我没有明确设置任何超时相关设置,对于执行存储过程,是否有任何超时设置(例如,如果无法从服务器检索到ADO.Net客户端的结果一段默认时间,则会有一些超时例外?)?

    using (SqlConnection currentConnection = new SqlConnection("Data Source=.;Initial Catalog=TestDB;Trusted_Connection=true;Asynchronous Processing=true")) { // check current batch conut currentConnection.Open(); using (SqlCommand RetrieveOrderCommand = new SqlCommand()) { RetrieveOrderCommand.Connection = currentConnection; RetrieveOrderCommand.CommandType = CommandType.StoredProcedure; RetrieveOrderCommand.CommandText = "prc_GetOrders"; RetrieveBatchCountCommand.Parameters.Add("@Count", SqlDbType.Int).Direction = ParameterDirection.Output; RetrieveBatchCountCommand.ExecuteNonQuery(); int rowCount = Convert.ToInt32(RetrieveOrderCommand.Parameters["@Count"].Value); } } 

正如gbn已经提到的,有两种类型的超时:

1)连接超时:这由连接字符串控制:

 Data Source=.;Initial Catalog=TestDB; Trusted_Connection=true;Asynchronous Processing=true 

如果您将Connect Timeout=120添加到此字符串,您的连接将尝试120秒打开然后中止。

 Data Source=.;Initial Catalog=TestDB; Trusted_Connection=true;Asynchronous Processing=true; Connect Timeout=120; 

2)命令超时:对于每个命令,您还可以指定超时 – 在取消查询之前,ADO.NET将等待该时间。 您在SqlCommand对象上指定:

  using (SqlCommand RetrieveOrderCommand = new SqlCommand()) { RetrieveOrderCommand.CommandTimeout = 150; } 

是的,可以设置2种超时

  1. 连接超时
  2. 命令超时

在VBA,.net等中默认为30秒

sqlconnection类中,有一个名称为ConnectionTimeout的属性。

这不能直接用于设置所需的连接超时值,因为它是只读的,即只实现了“get”并且没有在此属性上实现“set”。所以我们必须在连接字符串本身和集合中使用关键字“Connection Timeout”期望值。

EXI:

Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;Connection Timeout=30";(30 means 30 seconds)

30秒是建立与服务器连接的最长时间(如172.160.0.2或类似ADMINISTRATOR\\SQLEXPRESS )。如果它无法立即建立与服务器的连接,那么它将尝试最多30秒。

如果服务器有效且能够连接到服务器并且数据库名称或登录凭据无效,则此超时将不适用。它会立即抛出无效凭据或数据库的exception