I am trying to override the default SqlConnection
timeout of 15 seconds and am getting an error saying that the
property or indexer cann
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.
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.
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;
}
}
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.