阅读器关闭时read的尝试无效

这是类里的方法,执行完全没有问题的

public override SqlDataReader GetSqlDataReader(string Sql, params SqlParameter[] commandParameters)
    {
        SqlDataReader sdr = null;
        using (SqlConnection connection = GetSqlConnection())
        {
            SqlCommand command = new SqlCommand(Sql, connection);
            if (commandParameters != null)
            {
                foreach (SqlParameter parm in commandParameters)
                    command.Parameters.Add(parm);
            }
            connection.Open();
            sdr = command.ExecuteReader();
            connection.Close();
        }
        return sdr;
    }

 

而在调用该类中的此方法时却报“阅读器关闭时read的尝试无效”错误,调用方法如下:

public void setValue(string id)
        {
            try
            {
                SqlParameter[] paralist =
                    {
                    new   SqlParameter("@id", SqlDbType.Int)
                    };
                paralist[0].Value = Convert.ToInt32(id);
                string setSql = "select Air,class,discountRate,discountName,ei" +
                    ",bznotes from Classinfo where id=@id";
                sqlHelper = new sqlHelp();
                SqlDataReader sdr = null;
                sdr = sqlHelper.GetSqlDataReader(setSql, paralist);
                if (sdr != null)
                {
                    if (sdr.Read())
                    {
                        this.txtAir.Text = sdr["Air"].ToString();
                        this.txtCabin.SelectedText = sdr["class"].ToString();
                    }
                }
            }
            catch
            { }
        }

很不明白,在类中调试该方法完全没有问题,为什么在窗体中调用时去报这样的错误呢,后来看到

using (SqlConnection connection = GetSqlConnection())这句代码

而using为只要跳出了代码段就自动调用这个类实例的Dispose,因此也就释放了所有的资源,包括connection、command,所以SqlDataReader对象也就不能打开了!

注意:如果加了灰色的"connection.Open();"调用时也是会报错的.

所以最好这样:sdr = command.ExecuteReader(CommandBehavior.CloseConnection);

你可能感兴趣的:(read)