昨天一個朋友使用Repeater綁定數據源時,老是出現"閱讀器關閉時嘗試調用 FieldCount 無效。"錯誤。
我看了他的代碼,使用的是SqlHelper類下面的ExecuteReader方法,返回一個SqlDataReader進行綁定。
public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] cmdParms) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(CONN_STRING); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } }
然后,他自己又編寫了一個類,GetData,用其中的一個方法來調用SqlHelper.
public SqlDataReader GetReader() { using (SqlDataReader reader = SqlHelper.ExecuteReader(CommandType.StoredProcedure, "GetAllUser", null)) { return reader; } }
其中GetAllUser是一個不帶參數,查詢所有用戶的存儲過程,最后通過返回的reader進行數據源綁定。
他出現的這個錯誤,明顯是在讀取reader之前,reader已經被關閉(using的原因)。因此會讀不到數據,就會報那種錯誤。因此,把他的調用方法改了一下:
public SqlDataReader GetReader() { try { SqlDataReader reader=SqlHelper.ExecuteReader(CommandType.StoredProcedure, "GetAllUser", null); return reader; } catch (Exception) { return null; } }
這樣,就不會報錯了,UI層進行數據綁定也沒有任何問題。但是,隨之一個新的問題出現了:SqlDataReader沒有手動關閉,會不會造成連接池達到最大值?
我們注意到,在SqlHelper里面,使用到了CommandBehavior.CloseConnection,這個的作用是"關閉SqlDataReader 會自動關閉Sqlconnection." 也就是說,關閉Sqlconnection是在關閉SqlDataReader的前提下進行,還是需要手動關閉SqlDataReader。又要返回SqlDataReader,又要關閉它,怎么辦呢?有的網友提出:在return reader之前,先關閉reader,即進行reader.Close();
實際上這樣是不行的,會報與前面一樣的錯誤,在讀取數據之前,已經被關閉。
CommandBehavior.CloseConnection用於關閉數據庫連接,這是肯定的,但它會不會一起把SqlDataReader也一起關閉了呢。也就是說,用了CommandBehavior.CloseConnection,是不是就不用再手動關閉SqlDataReader了。
我們中以使用SqlHelper,然后在前台網頁里面進行測試
protected void bind() { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString()); conn.Open(); SqlCommand cmd = new SqlCommand("GetAllUser", conn); SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); repeater1.DataSource = sdr; repeater1.DataBind(); Response.Write(sdr.IsClosed.ToString()+"<br/>"); Response.Write(conn.State.ToString()); }
輸出的結果是
True
Closed
說明SqlConnection和SqlDataReader都已經被關閉了。
如果把CommandBehavior.CloseConnection去掉,輸出的結果則是:
False
Open
由此可見,使用了CommandBehavior.CloseConnection之后,讀取完數據后,系統自動關閉了SqlDataReader和SqlConnection。聽說當初微軟弄出CommandBehavior.CloseConnection的目的,就是為了解決數據庫的關閉問題的。
當然,我的數據量非常少,不能說明問題。希望更多的朋友說說自己的想法。