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);

                }

            }

        }

posted on 2019-04-02 15:31  xfgnongmin  阅读(200)  评论(0编辑  收藏  举报

导航