在一个数据库访问层中有类似以下的代码:
public  class Base
.........
    protected static string strConn = "Server=(local); User id=sa;Pwd=;Database=test";    public SqlDataReader ExecuteSqlDataReader(string strSQL)
   {  
    SqlConnection myCn = new SqlConnection(strConn); 
    SqlCommand myCmd = new SqlCommand(strSQL,myCn);
    try
       {
myCn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
if(myReader.Read())
{
  return myReader;

else
{
throw new Exception("Value Unavailable!");
}
       }
   catch(System.Data.SqlClient.SqlException e)
{
  throw new Exception(e.Message);
}
  finally
{
  myCn.Close();
}
然后在窗体代码中调用:
   Base Login = new Base ();
   string strSql="select * from table where sn='1'"; //在查询分析器中此SQL可查到一行记录
   SqlDataReader dr=Login.ExecuteSqlDataReader(strSql);
   while (dr.Read ())
{
TextBox1.Text=dr["username"].ToString ();
}
   结果提示: 阅读器关闭时READ的尝试无效
为什么呢?应该怎么写?

解决方案 »

  1.   

    finally
    {
      myCn.Close();
    }你把数据库链接给关闭了.
      

  2.   

    对,无论任何原因退出try块的时候,都会执行finally里的内容!
    你在finally中关闭了数据库连接对象,当然就不可用了!
      

  3.   

    System.Data.SqlClient.SqlDataReader sdr = mycmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
    这样当sdr.Close()时,数据连接也会自动关闭.