【问题标题】:Changing SqlConnection timeout更改 SqlConnection 超时
【发布时间】:2012-04-23 21:54:49
【问题描述】:

我正在尝试覆盖默认的 SqlConnection 超时 15 秒,但收到一条错误消息,提示

无法分配属性或索引器,因为它是只读的。

有没有办法解决这个问题?

using (SqlConnection connection = new SqlConnection(Database.EstimatorConnection))
{
   connection.Open();

   using (SqlCommand command = connection.CreateCommand())
   {
       command.CommandType = CommandType.StoredProcedure;
       connection.ConnectionTimeout = 180; // This is not working 
       command.CommandText = "sproc_StoreData";
       command.Parameters.AddWithValue("@TaskPlanID", order.Projects[0].TaskPlanID);
       command.Parameters.AddWithValue("@AsOfDate", order.IncurDate);

       command.ExecuteNonQuery();
    }
}

【问题讨论】:

  • 您的意思是在您尝试打开连接后设置连接超时吗?你是说命令超时吗?
  • 我真的,真的不明白他们为什么将属性设为只读。应该是读写的,IMO。
  • 连接后属性为只读。请参阅其他回复以进行讨论。 ConnectionTimeout 会在尝试连接时影响超时。为 Azure SQL DB 增加此值通常很有用。运行查询时,CommandTimeout 会影响超时。
  • @Sam Pearson 在连接打开之前它是读写的,即当 connection.Open();叫做。从此时开始,计时器已经开始运行。

标签: c# .net sql-server sqlconnection


【解决方案1】:

如果您想为特定查询提供超时,那么 CommandTimeout 是前进的方向。

它的用法是:

command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.

【讨论】:

  • 他不是在说命令超时,他是在说连接超时。
【解决方案2】:

您可以在连接字符串中设置超时值,但连接后它是只读的。你可以在http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx阅读更多内容

正如 Anil 所暗示的,ConnectionTimeout 可能不是您所需要的;它控制建立新连接时 ADO 驱动程序将等待多长时间。您的使用似乎表明需要等待比正常情况更长的时间才能执行特定的 SQL 查询,在这种情况下,Anil 是完全正确的;使用 CommandTimeout(即 R/W)更改单个 SqlCommand 的预期完成时间。

【讨论】:

    【解决方案3】:

    更简洁的方法是在 xml 文件中设置 connectionString,例如 Web.Confing(WepApplication) 或 App.Config(StandAloneApplication)。

     <connectionStrings>
        <remove name="myConn"/>
        <add name="myConn" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=qualitaBorri;Data Source=PC_NAME\SQLEXPRESS;Connection Timeout=60"/>
      </connectionStrings>
    

    通过代码你可以通过这种方式获得连接:

    public static SqlConnection getConnection()
    {
            string conn = string.Empty;
            conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
            SqlConnection aConnection = new SqlConnection(conn);
            return aConnection;
    }
    

    你可以设置ConnectionTimeout只有你创建一个实例。 创建实例时,您无需更改此值。

    【讨论】:

      【解决方案4】:

      您可以随时将其添加到您的连接字符串中:

      connect timeout=180;
      

      【讨论】:

      • 连接超时与 CommandTimeout 不同。连接超时是指解决与数据库的初始连接所需的时间。 CommandTimeout 更改特定查询的超时时间。
      • @m0g 我不明白为什么这不是公认的答案。这里的问题很可能是关于Connection Timeout,默认为15,是必须在Connection String 中定义的SqlConnection 的只读属性。海报列出的代码行专门尝试设置 SqlConnection.ConnectionTimeout。 Command Timeout 默认为 30,是完全不同的对象 SqlCommand 的读/写参数。问题的报错信息显示值为15,问题具体说的是SqlConnection,不是SqlCommand。
      • @BaconBits 发帖者描述和提出的问题与他想要的不同,因此接受的答案也不同。
      【解决方案5】:

      您可以将Connection Timeout=180; 添加到您的连接字符串中

      【讨论】:

      • 连接超时与 CommandTimeout 不同。连接超时是指解决与数据库的初始连接所需的时间。 CommandTimeout 更改特定查询的超时时间。
      【解决方案6】:

      你也可以使用SqlConnectionStringBuilder

      SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
      builder.ConnectTimeout = 10;
      using (var connection = new SqlConnection(builder.ToString()))
      {
          // code goes here
      }
      

      【讨论】:

        【解决方案7】:

        旧帖子,但当它出现在我正在搜索的内容时,我想我会在这个主题中添加一些信息。我打算添加评论,但我没有足够的代表。

        正如其他人所说:

        connection.ConnectionTimeout 用于初始连接

        command.CommandTimeout 用于单独的搜索、更新等。

        但是:

        connection.ConnectionTimeout 也用于提交和回滚事务。

        是的,这绝对是一个疯狂的设计决定。

        因此,如果您在提交或回滚时遇到超时,则需要通过连接字符串增加此值。

        【讨论】:

        • “Connection.ConnectionTimeout 也用于提交和回滚事务。是的,这绝对是一个疯狂的设计决策。”真的吗?我不相信这是真的。如果这是真的,那么任何持续时间超过 15 秒的连接超时的事务都会失败。你需要澄清一下。
        • 现在,如果您的意思是将其用作仅提交提交或回滚命令的超时时间,那么不……这不是一个疯狂的决定。它基本上是一个即时命令,应该立即返回,因为它只是向服务器发出提交或回滚的信号。如果它无法到达服务器并立即得到响应,那么这基本上是连接超时,这就是为什么使用这种方式是有意义的。
        【解决方案8】:

        您可以将连接超时设置为连接级别和命令级别。

        将“Connection Timeout=10”添加到连接字符串。现在连接超时为 10 秒。

        var connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;Connection Timeout=10";
        using (var con = new SqlConnection(connectionString))
        {
        
        }
        

        将CommandTimeout属性设置为SqlCommand

        var connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword";
        using (var con = new SqlConnection(connectionString))
        {
        
            using (var cmd =new SqlCommand())
            {
                cmd.CommandTimeout = 10;
            }
        
        }

        【讨论】:

        • 我认为你的回答是最干净的。我的应用程序是通过 CLI 实现的,我喜欢添加到连接字符串中。谢谢。
        【解决方案9】:

        你需要使用command.CommandTimeout

        【讨论】:

          【解决方案10】:

          我发现了一篇关于这个主题的优秀博文: https://improve.dk/controlling-sqlconnection-timeouts/

          基本上,您可以像这样在连接字符串中设置连接超时:

          Data Source=server;Initial Catalog=databaseUser Id=username;Password=password;Connect Timeout=30
          

          或者你像这样在命令对象上设置 ConnectionTimeout:

          sqlCommand.CommandTimeout = 30;
          

          请注意超时时间以秒为单位。

          此外,此超时不考虑由于服务器死机或过载等情况而导致的连接丢失。这些最终会触发 TCP 超时。请参阅博客文章以获取一个很好的扩展示例来处理它。

          【讨论】:

          • 您好,欢迎来到 SO!请阅读tour 和How do I write a good answer? 添加代码示例总是有帮助的。
          • 避免只使用链接,这些链接将来可能会改变。如有必要,添加一些有价值的提示和一些源代码以帮助澄清您的答案
          猜你喜欢
          • 1970-01-01
          • 2013-06-02
          • 2018-03-27
          • 1970-01-01
          • 1970-01-01
          • 2021-08-15
          • 2018-07-13
          • 2014-03-23
          • 2015-02-25
          相关资源
          最近更新 更多