zoukankan      html  css  js  c++  java
  • C#中存储过程和DataTable的应用

         存储过程p_OperatorDetails,有四个参数@sDatetime,@eDatetime,@operatorNo,@transdesc。其中@operatorNo和@transdesc为两个可选参数,通过这四个参数如何从存储过程里面提取自己想要的特定数据字段,方法各异,这里我用的是用DataTable的相关操作。

         首先打开数据库链接

                string strCon = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();
                SqlConnection conn = new SqlConnection(strCon);
                conn.Open();

         创建dataTable对象

                DataTable dt = new DataTable();

         创建SQLDataadapt对象来操作数据源存储过程p_OperatorDetails

                SqlDataAdapter da=new SqlDataAdapter("p_OperatorDetails",conn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

         创建sql参数并为其赋值

                SqlParameter p1 = new SqlParameter("@sDatetime", SqlDbType.DateTime);
                SqlParameter p2 = new SqlParameter("@eDatetime", SqlDbType.DateTime);
                SqlParameter p3 = new SqlParameter("@operatorNo", SqlDbType.Int);
                SqlParameter p4 = new SqlParameter("@transdesc", SqlDbType.VarChar);

                p1.Value = sTransactionDateStart;
                p2.Value = sTransactionDateEnd;
                if (sOperatorNo != "")
                {
                    p3.Value = Convert.ToInt32(sOperatorNo);
                    da.SelectCommand.Parameters.Add(p3);
                }
                else
                {
                    p3.Value = "";
                }
               
                if (sTransTypeNo != "")
                {
                    p4.Value = sTransTypeNo;
                    da.SelectCommand.Parameters.Add(p4);
                }
                else
                {
                    p4.Value = "";
                }
           
                da.SelectCommand.Parameters.Add(p1);
                da.SelectCommand.Parameters.Add(p2);

          通过SqlDataAdapter对象将得到的数据集填充到DataTable中去

                da.Fill(dt);

          注意直接得到的得到的DataTable对象是不能够进行sql操作的(可能我做的项目用这种方法并不适用于各位),关键的问题来了,我想要这个数据集里面的特点字段而不是整个存储过程所得到的数据集,我所使用的方法是用DataTable的Clone方法可能一张新的虚拟表来提供数据供我的报表使用。

                DataTable newdt = new DataTable();
                newdt = dt.Clone();

          DataTable中的数据不能够直接像实际数据表一样操作数据,但是也有它自己的方法

                newdt = dt.DefaultView.ToTable(false, new string[] { "BankCardId", "EmployeeName", "Deptname", "TransDesc", "DeviceDateTime", "remain","OperatorName" });

                至此,我想要的特定字段的虚拟表就出来了(报表用,做了几天发现这种方法还是最合适的,不知道各位大牛有没有更好的方法)。

  • 相关阅读:
    创建型-单例模式(Singleton)
    创建型-抽象工厂模式(Abstract Factory)
    创建型-工厂模式(Factory Method)
    excel数据查找/匹配/合并--vlookup公式使用
    【分库分表/读写分离】学习+整理
    java中main方法的参数的作用
    JVM指令码手册
    bug:Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
    sql:基础总结
    转:【host文件作用】
  • 原文地址:https://www.cnblogs.com/deng-c-q/p/4462923.html
Copyright © 2011-2022 走看看