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

本文探讨了在使用C#的using语句时引发的异常问题,特别是在数据库连接操作中。通过对比两种不同的实现方式,指出了using语句可能导致的资源提前释放问题,并给出了正确的处理方法。

 public static SqlDataReader GetReader(string sql, SqlParameter paras)
        {

            using (SqlConnection connection = new SqlConnection(SqlConnectionString))
            {
                SqlCommand command = new SqlCommand(sql, connection);
                command.Parameters.Add(paras);
                connection.Open();
                return command.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }

 

public static User GetUserByLoginId(string loginId)
        {
            string sql = "select * from users where loginId=@LoginId";
            int userStateId;
            int userRoleId;
            using (SqlDataReader reader = DBHelper.GetReader(sql, new SqlParameter("@LoginId", loginId)))
            {
                if (reader.Read())//在此发生异常
                  ........
            }
        }

如果把以上蓝色的代码改为

                try
            {
                SqlConnection connection = new SqlConnection(SqlConnectionString);
                SqlCommand command = new SqlCommand(sql, connection);
                command.Parameters.Add(paras);
                connection.Open();
                return command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

则正确,综上,发现是由于 using语句引起的,因为using的特性--"当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。"在此处也就是说已经释放了所有的资源,包括connection、command这样当然不能的到打开状态的SqlDataReader对象!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值