public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

解决方案 »

  1.   

    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    因为是返回一个连接,所以不能断开。
    CommandBehavior.CloseConnection
    表求  SqlDataReader 关闭时连接也会关闭。
    所以这要用户关闭rdr就可以了。
      

  2.   

    所以一定记得关闭并释放rdr就可以了。
      

  3.   

    cpp2017(幕白兄)
    正解CommandBehavior.CloseConnection
    CloseConnection 在执行该命令时,如果关闭关联的 DataReader 对象,则关联的 Connection 对象也将关闭。
      

  4.   

    如果方法内 关闭了连接 那返回的 DataReader  如何工作呢?
    代码设置了CommandBehavior.CloseConnection
    你在调用该方法后 记得 关闭Reader就可以关闭SqlConnection了。
      

  5.   

    最好把Reader出来的数据放到dataset中,接着关闭数据库,
      

  6.   

    这个我试过,用了CommandBehavior.CloseConnection,连接关闭后再返回reader会报错,
    好像是提示连接已关闭,CommandBehavior.CloseConnection表示连接随reader关闭而关闭
      

  7.   

    CommandBehavior.CloseConnection
    当你使用完DR,DR就自动关闭
      

  8.   

    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
     rdr 关闭后  连接就关闭了
      

  9.   

    虽然 建立了rdr 和conn的关联
    但是
    个人 觉得
    最好是 把 conn 的打开和关闭 显示再 使用函数的外面声明