SQL Server的超时设置

Geo*_*ge2 24 .net c# sql-server ado.net visual-studio-2008

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

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

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

  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);
            }
        }
    
    Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 43

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

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

Data Source=.;Initial Catalog=TestDB;
   Trusted_Connection=true;Asynchronous Processing=true
Run Code Online (Sandbox Code Playgroud)

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

Data Source=.;Initial Catalog=TestDB;
   Trusted_Connection=true;Asynchronous Processing=true;
   Connect Timeout=120;
Run Code Online (Sandbox Code Playgroud)

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

    using (SqlCommand RetrieveOrderCommand = new SqlCommand())
    {
       RetrieveOrderCommand.CommandTimeout = 150;
    }
Run Code Online (Sandbox Code Playgroud)

  • 还可能值得注意的是,连接字符串上的"连接超时"参数还控制SqlTransaction.Commit方法的超时时间. (9认同)
  • 对于连接,通常会看到SqlException(如果某些内容通常出错),SecurityException(如果部分信任环境中缺少权限)或ArgumentException(如果连接字符串无效).SqlCommand将SqlException作为常规异常,还有InvalidArgument或SecurityEXceptions,具体取决于您调用的方法 - 有关哪些方法引发异常的详细信息,请参阅MSDN文档(此处列出的内容太多) (2认同)

gbn*_*gbn 13

是的,可以设置2种超时

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

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

  • 在SSMS中,我得到"超时已过期.在操作完成之前已经过了超时时间,或者服务器没有响应." 你可以使用WAITFOR DELAY '00:00:40'来测试强制命令超时的40秒等待和异常.对于连接超时,您可以组成服务器名称并尝试连接. (2认同)