c#数据库訪问返回值类型为SqlDataReader时使用using时注意的问题

版权声明:本文为博主原创文章,未经博主同意不得转载。

https://blog.csdn.net/u010512579/article/details/24011761

在封装通用 SQLSERVER 数据可訪问方法时,假设返回值类型为 SqlDataReader ,那么在创建连接字符串的时候。我们不能写成例如以下

 public static  SqlDataReader ExecuteReader(string strSQL)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

{

            using (SqlCommand cmd = new SqlCommand(strSQL, connection))

            {

                try

                {

                    connection.Open();

                    SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                    return myReader;

                }

                catch (System.Data.SqlClient.SqlException ex)

                {

                    throw new Exception(ex.Message);

                }

            }

        }

}

你在使用using创建的时候,在SqlDataReader 赋值后return时,SqlConnection 就会被释放资源,连接就会被关闭。而我们传递过去的SqlDataReader 是引用类型,接收传递过去的SqlDataReader 的地方调用的时候,就会提示连接已经被关闭。无法调用,由于  using (SqlConnection connection = new SqlConnection(connectionString))在方法结束时,就把资源释放了,并关闭了连接。为了正常接收传递过去的SqlDataReader 。在创建连接的时候不能用using,正确的写法例如以下

 

 public static  SqlDataReader ExecuteReader(string strSQL)

        {

            SqlConnection connection = new SqlConnection(connectionString);

            using (SqlCommand cmd = new SqlCommand(strSQL, connection))

            {

                try

                {

                    connection.Open();

                    SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                    return myReader;

                }

                catch (System.Data.SqlClient.SqlException ex)

                {

                    throw new Exception(ex.Message);

                }

            }

        }

转载于:https://www.cnblogs.com/xfgnongmin/p/10642901.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值