SQL Query TimeOut - c#

I have a vb.net program that runs a stored function and fills a dataset. However, due to the amount of information pulled, sometimes it times out on certain databases.
How can I increase the timeout of the query so as not to get hit with a timeout?
In my form button I have the following code that is NOT working (it still times out and the program errors)
Me.1TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.1;Initial Catalog=Database;Persist Security Info=True;User ID=USER;Password=PASSWORD; Connection Timeout = 120"
Me.1TableAdapter.Fill(Me.Dataset.1, TodayDt, TodayEnd)
Me.2TableAdapter.Fill(Me.Dataset.1, TodayDt, TodayEnd)
I get the error message:
System.Data.SQLClient.SQLException: Timeout expired. The timeout period elapsed piror to the completion of the operation or the server is not responding.

A connection has a timeout, but so does the command running against the connection. That timeout is for how long to wait just trying to establish the connection. See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx
So assuming you're using a SqlCommand then set the CommandTimeout property of the command.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx

Related

SqlCommand Times Out, CommandTimeout and ConnectionTimeout both = 0

I'm running a large number of extracts from a SQL database via a C# Script Task within a SSIS package. The connection to the source is acquired from a connection manager within the package:
object rawConnection = Dts.Connections[sqlSpecItems["ConnectionManager"]].AcquireConnection(Dts.Transaction);
SqlConnection connectionFromCM = (SqlConnection)rawConnection;
(splSpecItems is a Dictionary object that supplies the name of the connection manager to use)
The ConnectionTimeout property of the connection manager is set to 0. The connection string generated for the CM is:
Data Source=MyDatabase;User ID=MyUserName;Initial Catalog=MyDatabaseName;Persist Security Info=True;Asynchronous Processing=True;Connect Timeout=0;Application Name=MyPackageApplicationName;
The connection is used to return a SqlDataReader object as follows:
private SqlDataReader GetDataReaderFromQuery(string sqlQueryToExecute)
{
// connect to server
SqlConnection sqlReaderSource = GetSourceSQLConnection();
// create command
SqlCommand sqlReaderCmd = new SqlCommand(sqlQueryToExecute, sqlReaderSource)
{
CommandType = CommandType.Text,
CommandTimeout = 0
};
// execute query to return data to reader
SqlDataReader sqlReader = sqlReaderCmd.ExecuteReader();
return sqlReader;
}
The operation fails with the error message:
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Logged start and end times for the operation are typically around 50s apart, but can be up to 120s.
The source database is a Business Central cloud hosted SQL db. The failures occur on a small number of specific extracts, the larger ones (although by no means large in absolute terms, c20k rows). When attempting to query these via SSMS, there is typically a delay as the data has to be fetched from the source into memory, which I suspect to be the reason for the timeout (notwithstanding the setting of timeout = 0 for the connection and command). Note that once the failure has happened once, the data is in memory and so it doesn't repeat if I restart the job.
I've looked at various answers on this site, as well as across other sites. Nothing I have seen so far has given me any idea of what I might try to resolve this problem. Any help would be appreciated.
So, I found the problem. Just in case it helps anyone else, the timeout wasn't throwing because of the reader. Rather, it was the SqlBulkCopy operation downstream of it that I pass the reader into. Adding:
bulkCopy.BulkCopyTimeout = 0;
Has cleared the problem...

Getting SQL Server timeout exception even with command timeout set to 0

I have set the command timeout to 0 as per the documentation in SQL Server. I'm indexing a large table, and still get an exception "Execution timeout expired". The timeout period elapsed prior to completion of the operation or the server is not responding. The server is responding as I watch it though the SQL Server Monitor.
Here is the pertinent code:
private void ExecuteQuery(string qStr)
{
using (SqlConnection cnx = new SqlConnection(_ConnectionString))
{
cnx.Open();
using (SqlCommand cmd = new SqlCommand(qStr, cnx))
{
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
}
}
}
This is the connection string
Data Source='tcp:aplace.database.windows.net,1433';Initial Catalog='SQL-Dev';User Id='user#place';Password='password';Connection Timeout=360
Why am I getting a execution timeout? I have the connection timeout set to 7200 seconds, also. I am indexing a 31 million rows table on one column.
First, connection timeout and command timeout are not the same thing. Make sure you understand the difference and are using them correctly.
Second, if this is from a web page, you also need to consider timeout values relating to the web server, etc.
Third, to verify that it is in fact a timeout issue, execute your index statement in SSMS and find out how long it takes. Since the actual indexing takes place on the SQL server no matter where it is called from, the indexing time should be roughly equal whether running from SSMS or your application.

How to increase the connect timeout on a SqlCommand?

I have around 7000 rows in excel and I want send them to another local computer with linked server. I increased connect timeout in my connections but I get the same time again with no result.
SqlCommand cmd9 = new SqlCommand("insert into [" + ConString + "].Database.dbo.ExpressE select * from ExpressE", conn);
cmd9.ExecuteNonQuery();
Error message is:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.
The SqlCommand has a property CommandTimeout that by default is set to 30 seconds. You can set it to a higher number of seconds, even set it to 0 if you want the command to wait forever if needed. The link to the MSDN includes an example about how to use that property.

SQL Server "The wait operation timed out" when inserting records on remote server, but not locally

There is a weird problem with a deployed Windows application that uses a remote connection string to SQL Server 2012.
When inserting records, the SQL Server times out after a relatively short time saying "The wait operation timed out". I'm not able to debug the deployed application to find out why it is happening and where in the code it is happening.
However, I don't get this error when using the same database on the development machine, with a local connection.
Generally the code used is:
void MapData( SqlTransaction transaction, Dictionary<int, IDataObject> items )
{
foreach ( var i in items )
{
transaction.Save( "CHECKPOINT" );
try
{
ImportItem( transaction, i );
}
catch ( Exception e )
{
transaction.Rollback( "CHECKPOINT" );
}
}
ReportStatus();
}
While this code has been working, I am uncertain about remote connections. We only have this one single case where it does NOT work.
What can it be?
Is there a more solid or performant approach than using Save() and Rollback() in a loop?
I don't want to use TransactionScope to spawn new "child" transactions.
Thanks!
Your transaction is taking too long (not sure if it's committing or rolling back). In order to understand why you'd have to run a trace to get performance metrics.
But to get it working you could increase your timeout. Set the SqlCommand CommandTimeout to a larger value or 0 (no timeout). Also, the connection timeout is used for the transaction timeout - usually an issue only on expensive rollbacks. You specify this in the connection string like Connection Timeout=30.

Sometimes getting Timeout expired (...) at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)

My website works fine most of the time, but sometimes I get timeout expired errors and can't do anything for 1-15 minutes. When error occurs for first time it is:
The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) (...)
And after that, if I try to refresh page I keep getting:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
(...).
Every connection that I use is either SqlDataSource, or opened in code like this:
SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Faktury_RebuildConnectionString"].ToString());
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
try{
myConnection.Open();
somecodehere()
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
Where my connection string in web.config is Data Source=xxx\;Initial Catalog=xxx;User ID=xxx;Password=xxx;Max Pool Size=100;.
I tried to turn off pooling and it didn't help. I checked if every connection is handled properly and it is. All SELECTs are good - means they don't take much time. Especially I can see that when application is working properly.
This error also occurs when I leave my site for some time (15 - 60 min) and enter it again for first time; then all I need to do is refresh it and it works fine then.
In times of this error SQL Server works fine and other website using mostly same select queries works fine.
Does anybody have suggestion what may be wrong there? I've run out of ideas.
Edit:
It would be useful to at least not having to refresh page after being idle for longer time and getting this one time timeout expired.
There are two main Timeout property in ADO.NET.
Connection Timeout for Connection. It could be solved by setting ConnectionTimeout property of Connection object in Connection String.
Timeout for Data access ( Command Object ). You can set CommandTimeout property to Command object. I recommend you set CommandTimeOut property to bigger one value. Try this. Please let me know whether this can handle this problem or not. If you have any further questions, please feel free to let me know.

Categories

Resources