如何在App.config中设置SQLCommandTimeout

6

我已经使用SQL数据库开发了一个Windows服务,目前我的数据库记录已经很多,因此查询的执行时间比较长,而默认的命令超时时间为30秒,但我希望将其增加到120秒。其中一个选项是:

com.CommandTimeout = 120;

但是我的应用程序中有许多方法,所以我希望从APP.config文件中设置它,这样它就适用于应用程序级别。请问有人可以告诉我如何实现这一点吗?

谢谢。


4
无法在app.config中配置此设置。 - Rajeev Kumar
在appSettings下添加一个新的命令超时设置。 - qxg
2个回答

6
最简单的方法是在<appSettings>中添加一个新条目,类似这样:
<appSettings>
    <add key="commandTimeout" value="3000" />
</appSettings>

之后,创建一个CommandFactory类来填充值。
class CommandFactory
{
    public static int CommandTimeout
    {
        get
        {
            int commandTimeout = 0;
            var configValue = ConfigurationManager.AppSettings["commandTimeout"];
            if(int.TryParse(configValue, out commandTimeout))
               return commandTimeout;
            return 120; 
        }
    }

    public static SqlCommand CreateCommand(SqlConnection connection)
    {
        var command = new SqlCommand()
        {
            Connection = connection,
            CommandTimeout = CommandTimeout
        };
        return command;
    }
}

现在,在您的代码中,不要仅仅实例化一个新的 SqlCommand,而是调用 CommandFactory 方法:

using(var command = CommandFactory.CreateCommand(yourConnection))
{
    //
}

-1

在 app.config 文件中使用此代码

<configuration>
  <appSettings>
    <add key="connectioStringName" value="Data Source=source;Initial Catalog=tableName;User Id=databaseName;Password=password;Connection Timeout=3000"/>
  </appSettings>
</configuration>

6
这将设置SqlConnectionConnectionTimeout属性,而不是命令超时时间。请参阅MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout(v=vs.110).aspx - RePierre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接