首页  ·  知识 ·  云计算
DataSet多表查询操作
香烟人生  http://www.cnblogs.com/sjkjsandy/  综合  编辑:dezai  图片来源:网络
一.源码及说明: Code 1using System; 2using System.Collections.Generic; 3using System.Data;

一.源码及说明:

 

Code
  1using System;
  2using System.Collections.Generic;
  3using System.Data;
  4
  5namespace Andy.DataSetHelper
  6{
  7    public class DataSetHelper
  8    {
  9
 10
 11        public DataSet ds;
 12
 13        private System.Collections.ArrayList m_FieldInfo;
 14        private string m_FieldList;
 15
 16        public DataSetHelper(ref DataSet DataSet)
 17        {
 18            ds = DataSet;
 19        }
 20        public DataSetHelper()
 21        {
 22            ds = null;
 23        }
 24        /**////


 25        /// 该方法根据给定的字段列表(FieldList)和表名(TableName),创建表结构,并返回表对象
 26        /// 给定的字段可来自创建了关系的两张表,如果是源表(子表)中的字段,直接写字段名即可。
 27        /// 如果是关系表(父表)中的字段,
 28        /// 字段前面须加上关系名称,格式如:relationname.fieldname
 29        /// FieldList语法:[relationname.]fieldname[ alias][,[relationname.]fieldname[ alias]]
 30        ///

 31        /// 生成新结构表的表名
 32        /// 源表名(子表)
 33        /// 生成新结构表的目标字段
 34        /// 具有目标结构的表对象
 35        public DataTable CreateJoinTable(string TableName, DataTable SourceTable, string FieldList)
 36        {
 37            if (FieldList == null)
 38            {
 39                throw new ArgumentException("You must specify at least one field in the field list.");
 40            }
 41            else
 42            {
 43                DataTable dt = new DataTable(TableName);
 44                ParseFieldList(FieldList, true);
 45                foreach (FieldInfo Field in m_FieldInfo)
 46                {
 47                    if (Field.RelationName == null)
 48                    {
 49                        DataColumn dc = SourceTable.Columns[Field.FieldName];
 50                        dt.Columns.Add(dc.ColumnName, dc.DataType, dc.Expression);
 51                    }
 52                    else
 53                    {
 54                        DataColumn dc = SourceTable.ParentRelations[Field.RelationName].ParentTable.Columns[Field.FieldName];
 55                        dt.Columns.Add(dc.ColumnName, dc.DataType, dc.Expression);
 56                    }
 57                }
 58                if (ds != null)
 59                    ds.Tables.Add(dt);
 60                return dt;
 61            }
 62        }
 63        /**////
 64        /// 该方法用于关联查询,可以指定条件(RowFilter),以及排序字段(Sort);
 65        /// 直接将查询结果存储到DestTable表对象中\n
 66        /// 在FieldList中的字段可以是关系表中的字段,但是它的前面必须加上关系名称,格式如:relationname.fieldname
 67        /// 用于指定查询条件的字段和用于排序的字段只能是源表中的字段,不能是关系表中的字段
 68        /// FieldList语法:[relationname.]fieldname[ alias][,[relationname.]fieldname[ alias]]
 69        ///

 70        /// 用于存储查询结果的表对象
 71        /// 源表名(子表)
 72        /// 查询结果的目标字段
 73        /// 查询条件
 74        /// 排序字段
 75        public void InsertJoinInto(DataTable DestTable, DataTable SourceTable, string FieldList, string RowFilter, string Sort)
 76        {
 77            if (FieldList == null)
 78            {
 79                throw new ArgumentException("You must specify at least one field in the field list.");
 80            }
 81            else
 82            {
 83                ParseFieldList(FieldList, true);
 84                DataRow[] Rows = SourceTable.Select(RowFilter, Sort);
 85                foreach (DataRow SourceRow in Rows)
 86                {
 87                    DataRow DestRow = DestTable.NewRow();
 88                    foreach (FieldInfo Field in m_FieldInfo)
 89                    {
 90                        if (Field.RelationName == null)
 91                        {
 92                            DestRow[Field.FieldName] = SourceRow[Field.FieldName];
 93                        }
 94                        else
 95                        {
 96                            DataRow ParentRow = SourceRow.GetParentRow(Field.RelationName);
 97                            DestRow[Field.FieldName] = ParentRow[Field.FieldName];
 98                        }
 99                    }
100                    DestTable.Rows.Add(DestRow);
101                }
102            }
103        }
104        /**////
105        /// 1.该方法用于关联查询,可以指定条件(RowFilter),以及排序字段(Sort);  
106        /// 2.将查询结果存储到名称为TableName的表对象中;  
107        /// 3.在FieldList中的字段可以是关系表中的字段,但是它的前面必须加上关系名称,格式如:relationname.fieldname;
108        /// 4.用于指定查询条件的字段和用于排序的字段只能是源表中的字段,不能是关系表中的字段;  
109        /// 5.FieldList语法:[relationname.]fieldname[ alias][,[relationname.]fieldname[ alias]]
110        ///

111        /// 查询结果表名
112        /// 源表名(子表)
113        /// 查询结果的目标字段
114        /// 查询条件
115        /// 排序字段
116        /// 查询结果对象
117        public DataTable SelectJoinInto(string TableName, DataTable SourceTable, string FieldList, string RowFilter, string Sort)
118        {
119            DataTable dt = CreateJoinTable(TableName, SourceTable, FieldList);
120            InsertJoinInto(dt, SourceTable, FieldList, RowFilter, Sort);
121            return dt;
122        }
123
124        private void ParseFieldList(string FieldList, bool AllowRelation)
125        {
126            /**//*
127             * 将FieldList中的字段转换为FieldInfo对象,并添加到集合m_FieldInfo中
128             *
129             * FieldList 用例:  [relationname.]fieldname[ alias],
130            */
131            if (m_FieldList == FieldList) return;
132            m_FieldInfo = new System.Collections.ArrayList();
133            m_FieldList = FieldList;
134            FieldInfo Field;
135            string[] FieldParts;
136            string[] Fields = FieldList.Split(',');
137            int i;
138            for (i = 0; i <= Fields.Length - 1; i++)
139            {
140                Field = new FieldInfo();
141                //转换别名,存储在Field.FieldAlias
142                FieldParts = Fields[i].Trim().Split(' ');
143                switch (FieldParts.Length)
144                {
145                    case 1:
146                        //没有别名
147                        break;
148                    case 2:
149                        Field.FieldAlias = FieldParts[1];
150                        break;
151                    default:
152                        throw new Exception("Too many spaces in field definition: '" + Fields[i] + "'.");
153                }
154                //转换字段名称和关系名称,分别存储在Field.FieldName和Field.RelationName中
155                FieldParts = FieldParts[0].Split('.');
156                switch (FieldParts.Length)
157                {
158                    case 1:
159                        Field.FieldName = FieldParts[0];
160                        break;
161                    case 2:
162                        if (AllowRelation == false)
163                            throw new Exception("Relation specifiers not permitted in field list: '" + Fields[i] + "'.");
164                        Field.RelationName = FieldParts[0].Trim();
165                        Field.FieldName = FieldParts[1].Trim();
166                        break;
167                    default:
168                        throw new Exception("Invalid field definition: " + Fields[i] + "'.");
169                }
170                if (Field.FieldAlias == null)
171                    Field.FieldAlias = Field.FieldName;
172                m_FieldInfo.Add(Field);
173            }
174        }
175
176    }
177    class FieldInfo
178    {
179        public string RelationName;
180        public string FieldName;    //源表的字段名;
181        public string FieldAlias;    //查询结果表中的字段名,即需要查询字段的别名;
182        public string Aggregate;
183    }
184}
 

 

二.使用方法:

1.在项目中添加引用

2.程序中添加命名空间,如:using Andy.DataSetHelper;

3.定义对象,并实例化,如:DataSetHelper dsHelper = new DataSetHelper(ref ds);   ds为需要操作的DataSet对象

4.调用查询方法,如:dsHelper.SelectJoinInto("查询结果表名", ds.Tables["源表名(子表)"], "查询结果的目标字段", "查询条件", "排序字段");  各参数的说明见前文。

5调用完成后,在ds中将有一张名称为“查询结果表名”的DataTable。

三.使用用例:

////////定义变量,并初始化

DataSet  ds = new DataSet();

DataSetHelper dsHelper = new DataSetHelper(ref ds);

GridView dataGrid1 = new GridView();

//////////创建第一张表Employees

DataTable dt = new DataTable("Employees");

dt.Columns.Add("EmployeeID",Type.GetType("System.Int32") );

dt.Columns.Add("FirstName", Type.GetType("System.String"));

dt.Columns.Add("LastName", Type.GetType("System.String"));

dt.Columns.Add("BirthDate", Type.GetType("System.DateTime"));

dt.Columns.Add("JobTitle", Type.GetType("System.String"));

dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));

dt.Rows.Add(new object[] {1, "Tommy", "Hill", new DateTime(1970, 12, 31), "Manager", 42});

dt.Rows.Add(new object[] {2, "Brooke", "Sheals", new DateTime(1977, 12, 31), "Manager", 23});

dt.Rows.Add(new object[] {3, "Bill", "Blast", new DateTime(1982, 5, 6), "Sales Clerk", 42});

ds.Tables.Add(dt); ///////添加到ds中

//////////创建第二张表Departments

dt = new DataTable("Departments");

dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));

dt.Columns.Add("DepartmentName", Type.GetType("System.String"));

dt.Rows.Add(new object[] {15, "Men's Clothing"});

dt.Rows.Add(new object[] {23, "Women's Clothing"});

dt.Rows.Add(new object[] {42, "Children's Clothing"});

ds.Tables.Add(dt); ///////添加到ds中

//////////添加关系

ds.Relations.Add("DepartmentEmployee", ds.Tables["Departments"].Columns["DepartmentID"], ds.Tables["Employees"].Columns["DepartmentID"]);

///////////////////条用方法

dsHelper.SelectJoinInto("EmpDept2", ds.Tables["Employees"], "FirstName,LastName,BirthDate BDate,DepartmentEmployee.DepartmentName Department", "JobTitle='Manager'", "DepartmentID");

////////////////////绑定结果

dataGrid1.SetDataBinding(ds, "EmpDept2");

本文作者:香烟人生 来源:http://www.cnblogs.com/sjkjsandy/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读