为EnterpriseLibrary设置Sql CommandTimeout

时间:2010-09-10 04:13:49

标签: c# sql

我有一个sql查询,执行时间超过30秒。我知道我需要为命令对象设置CommandTimeout来克服这个问题。但是,命令对象发生的第一个位置是企业库中的方法“LoadDataSet”。

我认为我不想在这里修改它。

有人可以向我建议一个合适的地方来设置吗?

谢谢!

2 个答案:

答案 0 :(得分:6)

试试这个:

dcCommand = dDatabase.GetSqlStringCommand(sSQLCommand);
dcCommand.CommandTimeout = 60;      //**This is the key statement**
dDatabase.LoadDataSet(dcCommand, dsDataSet , saTableNames);

而不是这个

dDatabase.LoadDataSet(CommandType.Text, sSQLCommand, dsDataSet , saTableNames);

答案 1 :(得分:0)

我已经开始使用Microsoft Enterprise Library了,在正常情况下,DB操作使用“Database”类提供的方法来满足需要。在某些情况下,对于长时间运行的查询,开发人员希望设置SqlCommand(或DbCommand)类的CommandTimeout属性。这将允许查询作为命令超时中设置的值长时间执行。

默认情况下,数据访问应用程序块在方法调用中不支持/采用简单的CommandTimeout参数(网上有许多可用的解决方法示例)。为了实现相同的最小变化,我添加了一个名为“WithCommandTimeOut”的简单函数,在“Microsoft.Practices.EnterpriseLibrary.Data.Database”类中使用timeOutSecond参数,该类返回“Database”类的相同实例。请参阅下面的更新代码段以了解代码更改。希望这能解决超时问题。

//Class Level Static Variables
//Used to reset to default after assigning in "PrepareCommand" static method
static int DEFAULT_COMMAND_TIMEOUT_RESET = 30;

//Default value when "WithCommandTimeOut" not called
static int COMMAND_TIMEOUT_FOR_THIS_CALL = DEFAULT_COMMAND_TIMEOUT_RESET; 

public Database WithCommandTimeOut(int timeOutSeconds)
{
    COMMAND_TIMEOUT_FOR_THIS_CALL = timeOutSeconds;
    return this;
}

protected static void PrepareCommand(DbCommand command, DbConnection connection)
{
    if (command == null) throw new ArgumentNullException("command");
    if (connection == null) throw new ArgumentNullException("connection");

    //Here is the magical code ----------------------------
    command.CommandTimeout = COMMAND_TIMEOUT_FOR_THIS_CALL;
    //Here is the magical code ----------------------------

    command.Connection = connection;

    //Resetting value to default as this is static and subsequent
    //db calls should work with default timeout i.e. 30
    COMMAND_TIMEOUT_FOR_THIS_CALL = DEFAULT_COMMAND_TIMEOUT_RESET;
}

实施例。

Database db = EnterpriseLibraryContainer.Current.GetInstance(Of Database)("SmartSoftware");
db.WithCommandTimeOut(0).ExecuteDataSet(CommandType.Text, query);