.net调用存储过程分页

存储过程1
create PROCEDURE  gettotalnums
(
@TableNames NVARCHAR(200),
@Filter nvarchar(200))
AS
    IF @Filter = ''
        SET @Filter = ' WHERE 1=1'
    ELSE
        SET @Filter = ' WHERE ' +  @Filter

    EXECUTE('select count(*) from '+@TableNames+' '+@Filter)

存储过程2
create    PROCEDURE [fenye]
@TableNames VARCHAR(200),    --表名,可以是多个表,但不能用别名
@PrimaryKey VARCHAR(100),    --主键,可以为空,但@Order为空时该值不能为空
@Fields    VARCHAR(200),        --要取出的字段,可以是多个表的字段,可以为空,为空表示select *
@PageSize INT,            --每页记录数
@CurrentPage INT,        --当前页,0表示第1页
@Filter VARCHAR(200) = '',    --条件,可以为空,不用填 where
@Group VARCHAR(200) = '',    --分组依据,可以为空,不用填 group by
@Order VARCHAR(200) = ''    --排序,可以为空,为空默认按主键升序排列,不用填 order by
AS
BEGIN
    DECLARE @SortColumn VARCHAR(200)
    DECLARE @Operator CHAR(2)
    DECLARE @SortTable VARCHAR(200)
    DECLARE @SortName VARCHAR(200)
    IF @Fields = ''
        SET @Fields = '*'
    IF @Filter = ''
        SET @Filter = 'WHERE 1=1'
    ELSE
        SET @Filter = 'WHERE ' +  @Filter
    IF @Group <>''
        SET @Group = 'GROUP BY ' + @Group

    IF @Order <> ''
    BEGIN
        DECLARE @pos1 INT, @pos2 INT
        SET @Order = REPLACE(REPLACE(@Order, ' asc', ' ASC'), ' desc', ' DESC')
        IF CHARINDEX(' DESC', @Order) > 0
            IF CHARINDEX(' ASC', @Order) > 0
            BEGIN
                IF CHARINDEX(' DESC', @Order) < CHARINDEX(' ASC', @Order)
                    SET @Operator = '<='
                ELSE
                    SET @Operator = '>='
            END
            ELSE
                SET @Operator = '<='
        ELSE
            SET @Operator = '>='
        SET @SortColumn = REPLACE(REPLACE(REPLACE(@Order, ' ASC', ''), ' DESC', ''), ' ', '')
        SET @pos1 = CHARINDEX(',', @SortColumn)
        IF @pos1 > 0
            SET @SortColumn = SUBSTRING(@SortColumn, 1, @pos1-1)
        SET @pos2 = CHARINDEX('.', @SortColumn)
        IF @pos2 > 0
        BEGIN
            SET @SortTable = SUBSTRING(@SortColumn, 1, @pos2-1)
            IF @pos1 > 0
                SET @SortName = SUBSTRING(@SortColumn, @pos2+1, @pos1-@pos2-1)
            ELSE
                SET @SortName = SUBSTRING(@SortColumn, @pos2+1, LEN(@SortColumn)-@pos2)
        END
        ELSE
        BEGIN
            SET @SortTable = @TableNames
            SET @SortName = @SortColumn
        END
    END
    ELSE
    BEGIN
        SET @SortColumn = @PrimaryKey
        SET @SortTable = @TableNames
        SET @SortName = @SortColumn
        SET @Order = @SortColumn
        SET @Operator = '>='
    END

  
    DECLARE @type varchar(50)
    DECLARE @prec int
    SELECT @type=t.name, @prec=c.prec
    FROM sysobjects o
    JOIN syscolumns c on o.id=c.id
    JOIN systypes t on c.xusertype=t.xusertype
    WHERE o.name = @SortTable AND c.name = @SortName

 
  
   
    IF CHARINDEX('char', @type) > 0
    SET @type = @type + '(' + CAST(@prec AS varchar) + ')'
    

    DECLARE @TopRows INT
    SET @TopRows = @PageSize * @CurrentPage + 1
    
    PRINT @type
    DECLARE @sql NVARCHAR(4000)

    SET @Sql =  'DECLARE @SortColumnBegin ' + @type + '
        SET ROWCOUNT ' + Cast(@TopRows  as VARCHAR(10))+ ' SELECT @SortColumnBegin=' +
    @SortColumn + ' FROM  ' + @TableNames + ' ' + @Filter + ' ' + @Group + ' ORDER BY ' + @Order + '
        SET ROWCOUNT ' + CAST(@PageSize AS  VARCHAR(10)) + '
        SELECT ' + @Fields + ' FROM  ' + @TableNames + ' ' + @Filter  + ' AND ' + @SortColumn + '' + @Operator + '@SortColumnBegin ' + ISNULL(@Group,'') + ' ORDER BY ' + @Order + ''

  -- Print(@sql)
  Exec(@sql)


END

 

 

public class DbHelper{
    public static SqlConnection getcon()
    {
        //string connectionstring = ConfigurationManager.ConnectionStrings["zhang"].ConnectionString;
        string connectionstring = ConfigurationManager.AppSettings["zhang"];
        SqlConnection dbconn = new SqlConnection(connectionstring);
        if (dbconn == null)
        {
            dbconn.Open();
        }
        else if (dbconn.State == ConnectionState.Closed)
        {
            dbconn.Open();
        }
        else if (dbconn.State == ConnectionState.Broken)
        {
            dbconn.Close();
            dbconn.Open();
        }

        return dbconn;
    }
    //返回数据集
    public static DataTable myDataAdapter(string str)
    {
        SqlConnection myconn = getcon();
        try
        {
            SqlDataAdapter odr = new SqlDataAdapter(str, myconn);
            DataSet ds = new DataSet();
            odr.Fill(ds);
            return ds.Tables[0];
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();
            myconn.Close();
        }
    }
    public static int ExcuteCommand(string sql)
    {
        SqlConnection myconn = getcon();
        int result = -1;
        try
        {
            SqlCommand cmd = new SqlCommand(sql, myconn);
            result = cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Close();
        }
        return result;
    }
   
    public static int ExecuteProcCommand(string proc)
    {
        SqlConnection myconn = getcon();
        SqlCommand cmd = new SqlCommand(proc, myconn);
        cmd.CommandType = CommandType.StoredProcedure;

        int result = -1;
        try
        {
            result = cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            myconn.Close();
            myconn.Dispose();
        }
        return result;
    }
    public static DataTable myDataAdapter(string str, params SqlParameter[] values)
    {
        SqlConnection myconn = getcon();
        try
        {
            SqlCommand cmd = new SqlCommand(str, myconn);
            cmd.Parameters.AddRange(values);
            SqlDataAdapter odr = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            odr.Fill(ds);
            return ds.Tables[0];
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }
    //更新、删除或插入数据
    public static void myCommand(string sql)
    {
        SqlConnection myconn = getcon();
        try
        {
            SqlCommand cmd = new SqlCommand(sql, myconn);
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }
    public static int Count(string sql)
    {
        SqlConnection myconn = getcon();
        int num = 0;
        try
        {
            SqlCommand cmd = new SqlCommand(sql, myconn);
            num = Convert.ToInt32(cmd.ExecuteScalar());
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
        return num;
    }
    public static void myCommand2(string sql, string vfile)
    {
        SqlConnection myconn = getcon();
        try
        {
            SqlCommand cmd = new SqlCommand(sql, myconn);
            cmd.Parameters.AddWithValue("@id", vfile);

            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }

    //判断数据是否存在
    public static bool myDataReader(string sql)
    {
        SqlConnection myconn = getcon();
        try
        {
            SqlCommand rcmd = new SqlCommand(sql, myconn);
            SqlDataReader reader = rcmd.ExecuteReader();
            bool ifread;
            if (reader.Read())
                ifread = true;
            else
                ifread = false;

            rcmd.Dispose();
            return ifread;
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }
    //读出目标数据
    public static string ReadOut(string sql, int field)
    {
        SqlConnection myconn = getcon();
        try
        {
            string result;
            SqlCommand objcmd = new SqlCommand(sql, myconn);
            SqlDataReader objdr = objcmd.ExecuteReader();
            if (objdr.Read())
            {
                objcmd.Dispose();
                return result = objdr[field].ToString();
            }
            else
            {
                objcmd.Dispose();
                return "没有该记录";
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }


    public static string ReadOut2(string sql)
    {
        SqlConnection myconn = getcon();
        try
        {
            string result;
            SqlCommand objcmd = new SqlCommand(sql, myconn);
            SqlDataReader objdr = objcmd.ExecuteReader();
            if (objdr.Read())
            {
                objcmd.Dispose();
                return result = objdr[0].ToString();
            }
            else
            {
                objcmd.Dispose();
                return "";
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }

    public static int ExecuteCommand(string sql, params SqlParameter[] values)
    {
        SqlConnection myconn = getcon();
        int result = -1;
        try
        {
            SqlCommand cmd = new SqlCommand(sql, myconn);
            cmd.Parameters.AddRange(values);
            result = cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
        return result;
    }
    public static int ExecuteCommand(string sql)
    {
        SqlConnection myconn = getcon();
        int result = -1;
        try
        {
            SqlCommand cmd = new SqlCommand(sql, myconn);

            result = cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
        return result;
    }
    //返回一条记录
    public static DataRow GetDataRow(string sql, string TableName)
    {
        SqlConnection myconn = getcon();
        try
        {
            SqlDataAdapter odr1 = new SqlDataAdapter(sql, myconn);
            DataSet ds = new DataSet();
            odr1.Fill(ds, TableName);
            return ds.Tables[0].Rows[0];
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            myconn.Dispose();

            myconn.Close();
        }
    }

    public static bool IsNumeric(string str)
    {
        Regex RegNum = new Regex(@"^[0-9]*[1-9][0-9]*$");

        str = str.Replace(" ", "");
        if (RegNum.IsMatch(str))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static string rootstr()
    {
        return HttpContext.Current.Server.MapPath("~").ToString();
    }
    public static bool AdminLimits(string _AdminID, int _start)
    {
        bool _limit = false;
      
        if (!string.IsNullOrEmpty(_AdminID))
        {
            try
            {

                if (GetUserLimits(_AdminID, _start) == "1")
                {
                    _limit = true;
                }
                else
                {
                    _limit = false;
                }
            }

            catch
            {
                _limit = false;
            }

        }

        return _limit;
    }


    public static string GetUserLimits(string _limitsStr, int _start)
    {
        string _tem = string.Empty;
        if (!string.IsNullOrEmpty(_limitsStr))
        {
            _tem = _limitsStr.Substring(_start, 1);
        }
        return _tem;
    }

     public static SqlDataReader GetReader(string safeSql)
        {
          
          SqlConnection conn = getcon();
            SqlCommand cmd = new SqlCommand(safeSql, conn);
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            reader.Close();
            return reader;
        }

        public static SqlDataReader GetReader(string sql, params SqlParameter[] values)
        {
          SqlConnection conn = getcon();
            SqlCommand cmd = new SqlCommand(sql, conn);
         
            cmd.Parameters.AddRange(values);
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            reader.Close();
            conn.Close();
            return reader;

        }

        public static DataTable GetDataSet(string safeSql)
        {
            SqlConnection conn = getcon();

            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand(safeSql, conn);
        
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            conn.Close();
            return ds.Tables[0];
        }
        public static DataTable GetDataSet(CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlConnection conn = getcon();
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand(cmdText, conn);
         
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            conn.Close();
            return ds.Tables[0];
        }
        public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();
        SqlConnection conn = getcon();
          
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                rdr.Close();
                conn.Close();
                return rdr;
              
        }
        public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = getcon())
            {
             
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                conn.Close();
                return val;
            }
        }
        public static object ExecuteScalar(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {

            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        public static void ExecuteNonQuery(string sql)
        {
          SqlConnection conn = getcon();
            SqlCommand cmd = new SqlCommand(sql,conn);
          
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        /// <summary>
        /// 传入SQL语句,返回int
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
      
        /// <summary>
        ///
        /// </summary>
        /// <param name="Name">需要分页的表明</param>
        /// <param name="pk">主键名</param>
        /// <param name="fields">需要取出的字段,留空则为*</param>
        /// <param name="pagesize">每页的记录数</param>
        /// <param name="CurrentPage">当前页</param>
        /// <param name="Filter">条件,可以为空,不用填 where</param>
        /// <param name="Group">分组依据,可以为空,不用填 group by</param>
        /// <param name="order">排序,可以为空,为空默认按主键升序排列,不用填 order by</param>
        /// <returns></returns>
        public static DataTable Pagedlist(string Name, string pk, string fields, int pagesize, int CurrentPage, string Filter, string Group, string order)
        {
            CurrentPage = CurrentPage - 1;
            DataTable dt = GetDataSet(CommandType.StoredProcedure, "fenye",
             new SqlParameter("@TableNames", Name),
             new SqlParameter("@PrimaryKey", pk),
             new SqlParameter("@Fields", fields),
             new SqlParameter("@PageSize", pagesize),
             new SqlParameter("@CurrentPage", CurrentPage),
             new SqlParameter("@Filter", Filter),
             new SqlParameter("@Group", Group),
             new SqlParameter("@Order", order)
             );
            return dt;
        }
        public static int fenye_num(string Name, string Filter)
        {
            return (int)ExecuteScalar(CommandType.StoredProcedure, "gettotalnums",
                    new SqlParameter("@TableNames", Name),
                        new SqlParameter("@Filter", Filter));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Name">需要分页的表明</param>
        /// <param name="pk">主键名</param>
        /// <param name="fields">需要取出的字段,留空则为*</param>
        /// <param name="pagesize">每页的记录数</param>
        /// <param name="CurrentPage">当前页</param>
        /// <param name="Filter">条件,可以为空,不用填 where</param>
        /// <param name="Group">分组依据,可以为空,不用填 group by</param>
        /// <param name="order">排序,可以为空,为空默认按主键升序排列,不用填 order by</param>
        /// <param name="objanp">传递aspnetpager控件</param>
        /// <returns></returns>
        public static DataTable Paged(string Name, string pk, string fields, int pagesize, int CurrentPage, string Filter, string Group, string order, AspNetPager objanp)
        {
            CurrentPage = CurrentPage - 1;
            DataTable dt = GetDataSet(CommandType.StoredProcedure, "fenye",
             new SqlParameter("@TableNames", Name),
             new SqlParameter("@PrimaryKey", pk),
             new SqlParameter("@Fields", fields),
             new SqlParameter("@PageSize", pagesize),
             new SqlParameter("@CurrentPage", CurrentPage),
             new SqlParameter("@Filter", Filter),
             new SqlParameter("@Group", Group),
             new SqlParameter("@Order", order)
             );
            objanp.RecordCount = fenye_num(Name, Filter);
            return dt;
        }

 CS 代码
public int page=1;

 private void binddata(int page)
    {
        DataTable dt = DbHelper.Paged("news", "id", "", AspNetPager1.PageSize, page, "", "", "id desc", AspNetPager1);
        this.Repeater1.DataSource = dt;
         this.Repeater1.DataBind();

            }
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        int currentpage = AspNetPager1.CurrentPageIndex;
        binddata(currentpage);
    }

posted @ 2011-03-14 11:43  放哨De老鼠  阅读(896)  评论(2编辑  收藏  举报