我在查询数据时,提示如题的提示,在网上查了一下,大概原因是因为SqlDataReader和SqlConnection在没使用完之前不能关闭,但是我把代码改了之后还是出现了如题一样的错误,请问一下到底是怎么回事?第一步执行的代码:public static void Proc(string strCommand, SqlParameter[] parameters, bool isText, ref SqlDataReader sqlDataReader)
        {
            using (SqlConnection con = DBOperation.CreateConnection())
            {
                SqlCommand cmd = null;
                try
                {
                    con.Open();
                    if (parameters != null)
                    {
                        cmd = DBOperation.CreateCommand(strCommand, con, parameters, isText);
                    }
                    else
                    {
                        cmd = DBOperation.CreateCommand(strCommand, con, null, isText);
                    }                    sqlDataReader = cmd.ExecuteReader();
                    //sqlDataReader.Close();
                }
                catch (Exception e)
                {
                    throw new SystemException(e.Message, e);
                }
                //finally
                //{
                    
                //    con.Close();
                //    con.Dispose();
                //}
            }
        }
第二步执行的代码,调用第一步的方法:public SqlDataReader GetDataReader(string strSql, bool isText)
        {
            SqlDataReader drData = null;
            DBOperation.Proc(strSql, null, isText, ref drData);
            //drData.Close();
            return drData;
        }
第三步,调用第二步的代码:BaseQuery query = new BaseQuery();
        Operator operate = new Operator();
        int isAdd = Convert.ToInt32(Request.QueryString["isAdd"].ToString());
        int n_id = Convert.ToInt32(Request.QueryString["n_id"].ToString());
        SqlDataReader dataReader = null;
        string strSql = string.Empty;        if (isAdd.Equals(1))
        {
            strSql = string.Format("select n_id,n_name from t_novel where n_id={0}", n_id);
            dataReader = query.GetDataReader(strSql, true);
            //加了这个判断语句之后,提示阅读器关闭时 HasRows 的尝试无效异常
              //去掉的话就提示如题的错误提示
            if (dataReader.HasRows)
            {
                this.lblNovelId.Text = dataReader[0].ToString() + "--";
                this.lblNovelName.Text = dataReader[1].ToString();
            }
            else
            {
                operate.showMsg(this.Page, "没有数据!");
            }
            dataReader.Close();
        }
        if (isAdd.Equals(2))
        {
        }=========================================
急知,有知道怎么解决的朋友麻烦告知,谢谢。

解决方案 »

  1.   

    不告。返回sqlDataReader的代码我直接删除。
      

  2.   

    呵呵!要知道using语句是另外一种写法,一种释放资源的写法,末尾为自动帮你调用dispose函数,所以:虽然你没有关闭数据库,但是系统帮你关闭了。。 如果非要返回这种类型,那么请不要用using写法,去掉试试看!
      

  3.   

    使用sqldatareader的时候,底层最好不要用using(){}
    原因很简单,在没真正要关闭的时候,系统会自动调用垃圾回收器清理掉了
      

  4.   

    为什么呢,难道sqlDataReader不好用吗?