Changing SqlConnection timeout

后端 未结 10 2118
孤街浪徒
孤街浪徒 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:43

    You can add Connection Timeout=180; to your connection string

    0 讨论(0)
  • 2020-12-25 09:50

    You need to use command.CommandTimeout

    0 讨论(0)
  • 2020-12-25 09:51

    You can set the timeout value in the connection string, but after you've connected it's read-only. You can read more at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx

    As Anil implies, ConnectionTimeout may not be what you need; it controls how long the ADO driver will wait when establishing a new connection. Your usage seems to indicate a need to wait longer than normal for a particular SQL query to execute, and in that case Anil is exactly right; use CommandTimeout (which is R/W) to change the expected completion time for an individual SqlCommand.

    0 讨论(0)
  • 2020-12-25 09:52

    Old post but as it comes up for what I was searching for I thought I'd add some information to this topic. I was going to add a comment but I don't have enough rep.

    As others have said:

    connection.ConnectionTimeout is used for the initial connection

    command.CommandTimeout is used for individual searches, updates, etc.

    But:

    connection.ConnectionTimeout is also used for committing and rolling back transactions.

    Yes, this is an absolutely insane design decision.

    So, if you are running into a timeout on commit or rollback you'll need to increase this value through the connection string.

    0 讨论(0)
  • 2020-12-25 09:54

    You could always add it to your Connection String:

    connect timeout=180;
    
    0 讨论(0)
  • 2020-12-25 09:55

    You can also use the SqlConnectionStringBuilder

    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
    builder.ConnectTimeout = 10;
    using (var connection = new SqlConnection(builder.ToString()))
    {
        // code goes here
    }
    
    0 讨论(0)
提交回复
热议问题