c# SqlHelper 封装SqlDataReader

        /// <summary>
        /// 执行sql语句返回一个DataReader
        /// 当返回DataReader的时候,注意:
        /// 1.Connection不能关闭
        /// 2.DataReader不能关闭
        /// 3.command对象执行ExecuteReader()的时候需要传递一个参数CommandBehavior.CloseConnection
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pms"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
        {
            SqlConnection con = new SqlConnection(constr);
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (pms != null)
                {
                    cmd.Parameters.AddRange(pms);
                }
                con.Open();
                //当调用ExecuteReader()方法的时候,如果传递一个CommandBehavior.CloseConnection参数,则表示将来当用户关闭reader的时候,系统会自动将Connection也关闭掉。
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return reader;
            }

        }

你可能感兴趣的:(c# SqlHelper 封装SqlDataReader)