如何延长 SQL 查询的超时时间

如何延长 SQL 查询的超时时间

问题描述:

这不是连接超时,因为与数据库的连接正常.问题是我正在调用的存储过程花费的时间超过 30 秒并导致超时.

This is not a connection timeout as a connection to the database is made fine. The problem is that the stored procedure that I'm calling takes longer than, say, 30 seconds and causes a timeout.

该函数的代码如下所示:

The code of the function looks something like this:

SqlDatabase db = new SqlDatabase(connectionManager.SqlConnection.ConnectionString);
return db.ExecuteScalar(Enum.GetName(typeof(StoredProcs), storedProc), parameterValues);

ExecuteScalar 调用超时.如何延长此功能的超时时间?

The ExecuteScalar call is timing out. How can I extend the timeout period of this function?

对于快速存储过程,它工作正常.但是,其中一个函数需要一段时间并且调用失败.当以这种方式调用 ExecuteScalar 函数时,我似乎找不到任何延长超时时间的方法.

For quick stored procedures, it works fine. But, one of the functions takes a while and the call fails. I can't seem to find any way to extend the timeout period when the ExecuteScalar function is called this way.

如果您正在使用 EnterpriseLibrary(看起来您是这样),请尝试以下操作:

If you are using the EnterpriseLibrary (and it looks like you are) try this:

 Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("ConnectionString");
 System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName");
 cmd.CommandTimeout = 600;
 db.AddInParameter(cmd, "ParameterName", DbType.String, "Value");

 // Added to handle paramValues array conversion
 foreach (System.Data.SqlClient.SqlParameter param in parameterValues) 
 {
     db.AddInParameter(cmd, param.ParameterName, param.SqlDbType, param.Value);
 }

 return cmd.ExecuteScalar();

编辑为直接根据注释处理 paramValues 数组.我还包括您的 ConnectionString 值:

Edited to handle the paramValues array directly based on the comments. I also included your ConnectionString value:

Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase(connectionManager.SqlConnection.ConnectionString);
System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName", parameterValues);
cmd.CommandTimeout = 600;
return cmd.ExecuteScalar();