今天碰到了一個查詢異常問題,上網(wǎng)查了一下,感謝原創(chuàng)和譯者
如果你使用的數(shù)據(jù)庫連接類是 the Data Access Application Blocks "SqlHelper" 或者 SqlClient Class , 你在執(zhí)行一個很費時的SQL 操作時候,可能就會碰到下面的超時異常。
---------------------------
--------------------------- Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. --------------------------- OK ---------------------------
你會說,我在連接字符串中已經 設置了 Connect Timeout=80000 ,并且數(shù)據(jù)庫中超時連接也是設置的值是一個很大的值。為啥到了30秒,仍然超時了呢??
這是因為: 你的設置并沒有問題,是你混淆了 SqlCommand.CommandTimeout 和 SqlConnection.ConnectionTimeout 這兩個的區(qū)別了。 你的連接字符串中的超時只是設置的 SqlConnection.ConnectionTimeout 的值,而不是設置的 SqlCommand.CommandTimeout 的值。 SqlHelper 中并沒有 SqlCommand.CommandTimeout 的相關設置。需要你自己設置。
下面是兩個的比較:
SqlCommand.CommandTimeout 獲取或設置在終止執(zhí)行命令的嘗試并生成錯誤之前的等待時間。 等待命令執(zhí)行的時間(以秒為單位)。默認為 30 秒。
SqlConnection.ConnectionTimeout 獲取在嘗試建立連接時終止嘗試并生成錯誤之前所等待的時間。 等待連接打開的時間(以秒為單位)。默認值為 15 秒。
一些更詳細的對這個問題的描述看: http://www./PrintSearchContent.asp?LINKID=357
這個問題可以算是 SqlHelper 設計的時候,一個考慮不周的地方吧。 SqlCommand.CommandTimeout 的默認值是30,對于我寫的大多數(shù)程序來說,這個值足夠了。所以一直都沒有發(fā)現(xiàn)SqlHelper的這個問題。今天在查本地一臺比較差的機子上生成一個超長帖子(近4000個回復)無響應的問題時候,才發(fā)現(xiàn)SQLHelper 存在的這個問題。
把command的Timeout屬性設置一下就ok了!
/// <summary>
/// 執(zhí)行查詢語句,返回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;  }  }
|