Changing SqlConnection timeout

后端 未结 10 2119
孤街浪徒
孤街浪徒 2020-12-25 09:22

I am trying to override the default SqlConnection timeout of 15 seconds and am getting an error saying that the

property or indexer cann

相关标签:
10条回答
  • 2020-12-25 09:59

    A cleaner way is to set connectionString in xml file, for example Web.Confing(WepApplication) or 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>
    

    By code you can get connection in this way:

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

    You can set ConnectionTimeout only you create a instance. When instance is create you don't change this value.

    0 讨论(0)
  • 2020-12-25 10:00

    If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.

    Its usage is:

    command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.
    
    0 讨论(0)
  • 2020-12-25 10:07

    You can set the connection timeout to the connection level and command level.

    Add "Connection Timeout=10" to the connection string. Now connection timeout is 10 seconds.

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

    Set the of CommandTimeout property to 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;
        }
    
    }
    0 讨论(0)
  • 2020-12-25 10:08

    I found an excellent blogpost on this subject: https://improve.dk/controlling-sqlconnection-timeouts/

    Basically, you either set Connect Timeout in the connection string, or you set ConnectionTimeout on the command object.

    Be aware that the timeout time is in seconds.

    0 讨论(0)
提交回复
热议问题