打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is n

今天碰到了一个查询异常问题,上网查了一下,感谢原创和译者

如果你使用的数据库连接类是 the Data Access Application Blocks "SqlHelper" 或者 SqlClient Class , 你在执行一个很费时的SQL 操作时候,可能就会碰到下面的超时异常。

---------------------------

---------------------------
Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
---------------------------
OK  
---------------------------

你会说,我在连接字符串中已经 设置了 Connect Timeout=80000 ,并且数据库中超时连接也是设置的值是一个很大的值。为啥到了30秒,仍然超时了呢??

这是因为:
你的设置并没有问题,是你混淆了  SqlCommand.CommandTimeout  和 SqlConnection.ConnectionTimeout 这两个的区别了。
你的连接字符串中的超时只是设置的 SqlConnection.ConnectionTimeout 的值,而不是设置的 SqlCommand.CommandTimeout 的值。
SqlHelper 中并没有 SqlCommand.CommandTimeout 的相关设置。需要你自己设置。

下面是两个的比较:

SqlCommand.CommandTimeout
获取或设置在终止执行命令的尝试并生成错误之前的等待时间。
等待命令执行的时间(以秒为单位)。默认为 30 秒。


SqlConnection.ConnectionTimeout
获取在尝试建立连接时终止尝试并生成错误之前所等待的时间。
等待连接打开的时间(以秒为单位)。默认值为 15 秒。

一些更详细的对这个问题的描述看:
http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=357

这个问题可以算是 SqlHelper 设计的时候,一个考虑不周的地方吧。
SqlCommand.CommandTimeout 的默认值是30,对于我写的大多数程序来说,这个值足够了。所以一直都没有发现SqlHelper的这个问题。今天在查本地一台比较差的机子上生成一个超长帖子(近4000个回复)无响应的问题时候,才发现SQLHelper 存在的这个问题。

 

把command的Timeout属性设置一下就ok了!

 /// <summary>
    
/// 执行查询语句,返回DataTable
    
/// </summary>
    
/// <param name="SQLString">查询语句</param>
    
/// <param name="commTime">设置查询Timeout</param>
    
/// <returns>用于复杂查询</returns>
    public static DataTable GetDataTable(string SQLString,int commTime)
    {
        string connectionString = System.Configuration.ConfigurationManager.AppSettings["connectionString"];
        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
        {
            DataTable dt = new DataTable();
            try
            {
                connection.Open();
                System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(SQLString, connection);
                comm.CommandTimeout = commTime;
                da.SelectCommand = comm;
                da.Fill(dt);
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            return dt;
        }
    }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
编写自己的高效分页SqlHelper
连接数据库的三种方式
ASP.NET系统开发(一):层层递进之SQLHelper助手类的持续优化
C#开发学习
sql 连接超时问题
sql server中批量插入与更新两种解决方案分享
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服