网站建设厂家,中小企业网贷平台,移动网站开发公司,做网站软件A开头的版权声明#xff1a;本文为博主原创文章#xff0c;未经博主同意不得转载。https://blog.csdn.net/u010512579/article/details/24011761 在封装通用 SQLSERVER 数据可訪问方法时#xff0c;假设返回值类型为 SqlDataReader ,那么在创建连接字符串的时候。我们不能写成例如以… 版权声明本文为博主原创文章未经博主同意不得转载。 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