浩晨众云网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
昨天一个朋友使用Repeater绑定数据源时,老是出现"阅读器关闭时尝试调用 FieldCount 无效。"错误。

创新互联IDC提供业务:达州主机托管,成都服务器租用,达州主机托管,重庆服务器租用等四川省内主机托管与主机租用业务;数据中心含:双线机房,BGP机房,电信机房,移动机房,联通机房。
我看了他的代码,使用的是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()+"
 
");- Response.Write(conn.State.ToString());
 - }
 
输出的结果是
True
Closed
说明SqlConnection和SqlDataReader都已经被关闭了。
如果把CommandBehavior.CloseConnection去掉,输出的结果则是:
False
Open
由此可见,使用了CommandBehavior.CloseConnection之后,读取完数据后,系统自动关闭了SqlDataReader和SqlConnection。听说当初微软弄出CommandBehavior.CloseConnection的目的,就是为了解决数据库的关闭问题的。
当然,我的数据量非常少,不能说明问题。希望更多的朋友说说自己的想法。