zoukankan      html  css  js  c++  java
  • C#学习-执行存储过程

    使用存储的优点

    1.执行更快。直接写sql脚本会有个解析编译的过程。

    2.修改方便。当业务改变时,只需要改存储过程,不需要修改C#代码

    3.传递Sql脚本数据相对更小

    缺点:

    1.使用存储过程,数据库移植性差

    2.把业务放到了存储过程里,相当于把处理业务的压力放到了数据库里面。

    存储过程的脚本:

    --分页原理:越过多少条,取多少条
    --创建一个存储过程
    create proc P_LoadPageData
        --参数
        @pageIndex int,
        @pageSize int,
        @total int out
    as
    select top(@pageSize) * from QunList where id not in
    (
        select top((@pageIndex-1)*@pageSize) id from QunList order by id
    )
    order by id
    select @total=count('a') from QunList
    select @total
    
    --执行存储过程
    declare @total int
    exec P_LoadPageData 2,5,@total out
    select @total

    C#中代码

    //如果用了输出参数,那么就用SQLDataAdapter就可以了,用SQLDataReader会拿不到输出参数
    string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
    //创建一个DateSet,用来保存查询出的数据
    //可以把DataSet比作数据库;把DataSet.Table比作数据库中的表
    DataSet ds=new DataSet();
    //设置输出参数
    SqlParameter totalParameter=new SqlParameter("@total",SqlDbType.Int);
    totalParameter.Direction = ParameterDirection.Output;
    using (SqlConnection conn = new SqlConnection(connstr))
    {
        conn.Open();
        using (SqlDataAdapter adapter = new SqlDataAdapter("P_LoadPageData", conn))
        {
            //设置为存储过程
            adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
            adapter.SelectCommand.Parameters.Add(new SqlParameter("@pageIndex", 5));
            adapter.SelectCommand.Parameters.Add(new SqlParameter("@pageSize", 7));
            //输出参数的用法
            adapter.SelectCommand.Parameters.Add(totalParameter);
            adapter.Fill(ds);
        }
    }
    //取得输出参数的值
    int total = (int) totalParameter.Value;
    var table = ds.Tables[0];
    更多精彩内容请看:http://www.cnblogs.com/2star
  • 相关阅读:
    Java calendar类学习笔记
    Anaconda 学习笔记
    第八周作业
    第七次作业
    第六周作业
    第五次作业
    用户调研方法之焦点小组
    第三周作业
    软件工作量的评估方法有哪些
    软件质量保证与测试(--作业--)
  • 原文地址:https://www.cnblogs.com/kimisme/p/4360718.html
Copyright © 2011-2022 走看看