秋枫思语

Keep It Simple and Stupid.

原创 ADO.NET中的多数据表操作浅析—读取收藏

新一篇: ADO.NET中的多数据表操作浅析—修改 | 旧一篇: Implementing the Singleton Pattern in C#[转载]

ADO.NET中的多数据表操作浅析—读取

作者:郑佐        2004-8-5

         在开发基于.NET平台的数据库应用程序时,我们一般都会用到DataSet,作为ADO.NET的核心类它为我们提供了强大的功能,而整个看上去就像是放在内存内的一个小型数据库,内部包括了DataTableDataViewDataRowDataColumnConstraint以及DataRelation。当初看到它时真的是有点兴奋。

         下面根据我的一些经验来举例说明在ADO.NET中的多表填充、关联表更新以及多个Command对象执行过程中启用事务的操作。欢迎大家交流,或在Blog上留言。

        

一、准备工作

         对于NorthWind数据库大家都比较熟悉,所以这里拿它为例,我把Customers(客户表)Orders(订单表)Order Details(订单详细表)合起来建立了一个类型化的数据集,类型名称为DatasetOrders,每个表只包括一些字段,下面是在Visual Studio .NET中建立的一个截图:



1-1

上面建立了两个关系表示为Customers > Orders >Order Details。因为Orders表的OrderID字段为自动增长列,这里把就把它的AutoIncrementSeedAutoIncrementStep值设置成了-1,这在实际添加订单的过程中可能会比较明显,不过不设也没问题。

        

二.填充数据集

建立一个窗体程序来演示实际的操作,界面如下:

2-1

整个应用程序就是一个Form,上面的三个DataGrid分别用来显示相关表的数据,不过他们是互动的。另外的两个单选框用来决定更新数据的方式,两个按钮正如他们的名称来完成相应的功能。

这里我们用一个DataAdapter来完成数据集的填充,执行的存储过程如下:

CREATE PROCEDURE GetCustomerOrdersInfo

AS

SELECT CustomerID,CompanyName,ContactName FROM Customers WHERE CustomerID LIKE 'A%'

 

SELECT OrderID,OrderDate,CustomerID FROM Orders  WHERE CustomerID IN

(SELECT CustomerID FROM Customers WHERE CustomerID LIKE 'A%')

 

SELECT OrderID,ProductID,UnitPrice,Quantity,Discount FROM [Order Details] WHERE OrderID IN

(SELECT OrderID FROM Orders  WHERE CustomerID IN

(SELECT CustomerID FROM Customers WHERE CustomerID LIKE 'A%'))

 

GO

 

为了减少数据量,这里只取了CustomerID’A’开头的数据。

建立DataAccess类来管理窗体同数据层的交互:

using System;

using System.Data;

using System.Data.SqlClient;

using Microsoft.ApplicationBlocks.Data;

 

namespace WinformTest

{

     public class DataAccess

     {

         private string _connstring = "data source=(local);initial catalog=Northwind;uid=csharp;pwd=c#.net2004;";

         private SqlConnection _conn;

         ///构造函数

public DataAccess()

         {

              _conn = new SqlConnection(_connstring);

}

下面的函数完成单个数据适配器来完成数据集的填充,

public void FillCustomerOrdersInfo(DatasetOrders ds)

          {

              SqlCommand comm = new SqlCommand("GetCustomerOrdersInfo",_conn);

              comm.CommandType = CommandType.StoredProcedure;

              SqlDataAdapter dataAdapter = new SqlDataAdapter(comm);

              dataAdapter.TableMappings.Add("Table","Customers");

              dataAdapter.TableMappings.Add("Table1","Orders");

              dataAdapter.TableMappings.Add("Table2","Order Details");

              dataAdapter.Fill(ds);

         }

如果使用SqlHelper来填充那就更简单了,

         public void FillCustomerOrdersInfoWithSqlHelper(DatasetOrders ds)

         {             SqlHelper.FillDataset(_connstring,CommandType.StoredProcedure,"GetCustomerOrdersInfo",ds,new string[]{"Customers","Orders","Order Details"});

         }

叉开话题提一下,Data Access Application Block 2.0中的SqlHelper.FillDataset这个方法超过两个表的填充时会出现错误,其实里面的逻辑是错的,只不过两个表的时候刚好凑巧,下面是从里面截的代码:

private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType,

              string commandText, DataSet dataSet, string[] tableNames,

              params SqlParameter[] commandParameters)

         {

              if( connection == null ) throw new ArgumentNullException( "connection" );

              if( dataSet == null ) throw new ArgumentNullException( "dataSet" );

              SqlCommand command = new SqlCommand();

              bool mustCloseConnection = false;

              PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );

              using( SqlDataAdapter dataAdapter = new SqlDataAdapter(command) )

              {

                   if (tableNames != null && tableNames.Length > 0)

                   {

                       string tableName = "Table";

                       for (int index=0; index < tableNames.Length; index++)

                       {

                            if( tableNames[index] == null || tableNames[index].Length == 0 )

                                 throw new ArgumentException( "The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames" );

                            tableName += (index + 1).ToString();//这里出现错误

                       }

                   }

                   dataAdapter.Fill(dataSet);

                   command.Parameters.Clear();

              }

              if( mustCloseConnection )

                   connection.Close();

         }

 

这里把tableName += (index + 1).ToString();修改成

dataAdapter.TableMappings.Add((index>0)?(tableName+index.ToString()):tableName, tableNames[index]);就能解决问题。

 

接下来看看窗体程序的代码:

public class Form1 : System.Windows.Forms.Form

     {

         private DataAccess _dataAccess;

         private DatasetOrders _ds;

         //……

         //构造函数

         public Form1()

         {

              InitializeComponent();

              _dataAccess = new DataAccess();

              _ds = new DatasetOrders();

              _ds.EnforceConstraints = false; //关闭约束检查,提高数据填充效率

              this.dataGridCustomers.DataSource = _ds;

              this.dataGridCustomers.DataMember = _ds.Customers.TableName;

              this.dataGridOrders.DataSource = _ds;

              this.dataGridOrders.DataMember = _ds.Customers.TableName+"."+_ds.Customers.ChildRelations[0].RelationName;

              this.dataGridOrderDetails.DataSource = _ds;

              this.dataGridOrderDetails.DataMember = _ds.Customers.TableName+"."+_ds.Customers.ChildRelations[0].RelationName+"."+_ds.Orders.ChildRelations[0].RelationName;

         }

对于上面的三个表的动态关联,你也可以使用SetDataBinding方法来完成数据的动态绑定,而不是分别指定DataGrideDataSourceDataMemger属性。

this.dataGridCustomers.SetDataBinding(_ds,_ds.Customers.TableName);

this.dataGridOrders.SetDataBinding(_ds,_ds.Customers.TableName+"."+_ds.Customers.ChildRelations[0].RelationName);

this.dataGridOrderDetails.SetDataBinding(_ds,_ds.Customers.TableName+"."+_ds.Customers.ChildRelations[0].RelationName+"."+_ds.Orders.ChildRelations[0].RelationName);

}

数据填充事件处理如下:                        

private void buttonFillData_Click(object sender, System.EventArgs e)

         {

              _ds.Clear();//重新填充数据集

              _dataAccess.FillCustomerOrdersInfo(_ds);

              //_dataAccess.FillCustomerOrdersInfoWithSqlHelper(_ds);

         }

执行上面的事件处理函数我们会看到数据显示到对应的DataGrid上,如(图2-1)所示。

如果使用数据读取器获取多表纪录下面是实现的一种方式(参考):

SqlCommand comm = new SqlCommand("GetCustomerOrdersInfo",_conn);

comm.CommandType = CommandType.StoredProcedure;

_conn.Open();

SqlDataReader reader = comm.ExecuteReader();

do

{

     while(reader.Read())

     {

         Console.WriteLine(reader[0].ToString());//获取数据代码

     }

}while(reader.NextResult());

Console.ReadLine();

_conn.Close();

 

发表于 @ 2004年08月06日 14:17:00|评论(loading...)|编辑

新一篇: ADO.NET中的多数据表操作浅析—修改 | 旧一篇: Implementing the Singleton Pattern in C#[转载]

评论

#秋枫 发表于2005-03-17 09:24:00  IP:
TrackBack来自《对以前的一些文章提供程序源代码》

Ping Back来自:blog.csdn.net
#mars 发表于2004-08-10 10:23:00  IP: 222.64.145.*
建议大哥把所有的问号都去掉
#joard 发表于2004-08-13 11:21:00  IP: 218.197.118.*
能把源代码发一份给我吗?
joard0118@hotmail.com

谢谢
#秋枫 发表于2004-08-18 18:51:00  IP: 211.140.56.*
问号已经去掉了,可能是ftb的原因.
#bing717@tom.com 发表于2004-10-26 15:14:00  IP: 221.208.56.*
能给我发过来一份原带码吗?谢谢
#bing717@tom.com 发表于2004-10-26 15:15:00  IP: 221.208.56.*
bing717@tom.com
#tsys2000 发表于2004-12-28 10:53:00  IP: 220.194.209.*
tsys2000@163.net

大哥能发份源码吗?谢谢
#欧阳 发表于2005-03-16 10:56:00  IP: 218.106.119.*
ouyangguang219@163.com
能发份原代码吗?谢谢
#check 发表于2005-03-28 16:51:00  IP: 202.118.178.*
请求源代码!!!
chenanlin2002@163.com
#wn 发表于2005-04-15 15:21:00  IP: 218.61.56.*
请求源代码!!!
jzhxwan@163.com
#liao 发表于2005-04-21 17:07:00  IP: 218.17.60.*
发一份源码给我好吗?代码我没有看懂,想调试研究一下.
#秋枫 发表于2005-04-22 21:04:00  IP: 61.175.135.*
这里都有了,怎么不看一下.
http://blog.csdn.net/zhzuo/archive/2005/03/17/321820.aspx
#海狼 发表于2005-06-06 09:46:00  IP: 61.186.252.*
這裡還是不能解決我的問題,請各位幫忙看一下!
http://blog.csdn.net/zhzuo/archive/2004/08/06/67016.aspx
#jigang 发表于2005-07-09 09:58:00  IP: 61.186.252.*
jigang1030@163.com

大哥能发份源码吗?谢谢
#xuwencan 发表于2005-07-07 16:35:00  IP: 61.186.252.*
请求源码
xuwencan@263.net
先谢谢了
#詹昌昊 发表于2005-09-13 16:12:00  IP: 211.100.21.*
我也想要源代码

有空发一份我吧!zchwrok@21cn.com
#秋枫 发表于2005-09-15 11:50:00  IP: 211.100.21.*
to:zchwrok@21cn.com
已经发了一份给你。
#xxd 发表于2005-12-05 17:09:00  IP: 218.22.21.*
我也想要源码
tanj@ustc.edu.cn
#hedgehog 发表于2006-01-18 11:38:00  IP: 219.137.37.*
请给我发一份源码好吗?
allenzee@hotmail.com
#AIG330 发表于2006-03-21 11:04:00  IP: 219.149.153.*
做了下,但没有你的那种效果.
能给我发一份源码吗?3Q!
kelelong@hotmail.com
#mmems 发表于2006-03-28 14:57:00  IP: 218.16.41.*
能否也發一份給我學習一下﹖謝謝
lshmmems@gmail.com
#mengxiang 发表于2006-05-20 10:39:00  IP: 10.255.6.*
能不能发给我一份
mengxiang1618@163.com
#SUN 发表于2006-06-09 17:02:00  IP: 220.132.160.*
給我一份源代碼
yaolintm@163.com
#goneaway 发表于2006-06-12 09:15:00  IP: 222.90.112.*
能否给我一份源代码,谢谢。goneaway@sohu.com。
#給我一份源代碼  发表于2006-07-05 13:05:00  IP: 219.139.209.*
給我一份源代碼
six_six_2005@163.com
#www 发表于2008-05-03 13:50:37  IP: 221.237.194.*
可以给我发一份源码不?
lssx1000@163.com
#longlong1234 发表于2008-06-01 22:13:53  IP: 58.217.251.*
可以给我一份缘代码吗 谢谢 badboy_long123@126.com
发表评论  


登录
Csdn Blog version 3.1a
Copyright © 秋枫