在C# 中Sql 执行超时的问题

来源:互联网 发布:京东微信小程序源码 编辑:程序博客网 时间:2024/04/29 06:32

解决方法:

C#代码
SqlCommand selectCommand = new SqlCommand(queryText,this.openConnection());
//得到Web.config里DB_ConnectionString中Connection Timeout=90
selectCommand.CommandTimeout = cn.ConnectionTimeout;
或者
SqlCommand selectCommand = new SqlCommand(queryText,this.openConnection());
selectCommand.CommandTimeOut=0;

Web.config(.NET 2005)
<connectionStrings>
<add name="DB_ConnectionString" connectionString="Data Source=xxx.xxx.xxx.xxx;Initial Catalog=DB NAME;Persist Security Info=false;User ID=sa;Password=sa;Connection Timeout=90;" providerName="System.Data.SqlClient"/>
</connectionStrings>

CommandTimeout 属性

指示执行命令期间在终止尝试和产生错误之前需等待的时间。

设置和返回值

设置或返回 Long 值,该值指示等待命令执行的秒数。默认值为 30。

说明

用 Connection 对象或 Command 对象的 CommandTimeout 属性来允许因网络拥挤或服务器负载过重产生的延迟而取消 Execute 方法调用。如果在 CommandTimeout 属性设置的时间间隔内未执行完命令,将产生错误,并且 ADO 取消该命令。如果将属性设置为零,ADO 将一直等待到命令执行完毕。请确保正在为其编写代码的提供者和数据源支持CommandTimeout 功能。

Connection 对象的 CommandTimeout 设置对同一Connection Command 对象上的 CommandTimeout 设置没有影响,即 Command 对象的CommandTimeout 属性不继承 Connection 对象的 CommandTimeout 值。

Connection 对象上,打开 Connection 后,CommandTimeout 属性将保持为读/写。

ConnectionTimeout 属性

指示在终止尝试和产生错误前建立连接期间所等待的时间。

设置和返回值

设置或返回指示等待连接打开的时间的长整型值(单位为秒)。默认值为 15。

说明

如果由于网络拥塞或服务器负载过重导致的延迟使得必须放弃连接尝试时,请使用 Connection 对象的 ConnectionTimeout 属性。如果打开连接前所经过的时间超过 ConnectionTimeout 属性上设置的时间,将产生错误,并且 ADO 将取消该尝试。如果将该属性设置为零,ADO 将无限等待直到连接打开。请确认正在对其编写代码的提供者会支持ConnectionTimeout 功能。

连接关闭时 ConnectionTimeout 属性为读/写,而打开时其属性为只读。

原创粉丝点击