[c#] Changing SqlConnection timeout

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

property or indexer cannot be assigned because it is read only.

Is there a way around this?

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();
    }
}

This question is related to c# .net sql-server sqlconnection

The answer is


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.


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.


You need to use command.CommandTimeout


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


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.


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.


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;
    }

}

You can also use the SqlConnectionStringBuilder

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

You could always add it to your Connection String:

connect timeout=180;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to sqlconnection

How to write connection string in web.config file and read from it? How to run multiple SQL commands in a single SQL connection? SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application Changing SqlConnection timeout How to use the ConfigurationManager.AppSettings Check if SQL Connection is Open or Closed in a "using" block is a SqlConnection closed on return or exception?