DataSet 多表更新方式

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

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

        

一、准备工作

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

 


图1-1

上面建立了两个关系表示为Customers —> Orders —>Order Details。因为Orders表的OrderID字段为自动增长列,这里把就把它的AutoIncrementSeed和AutoIncrementStep值设置成了-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方法来完成数据的动态绑定,而不是分别指定DataGride的DataSource和DataMemger属性。

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();

 

三、更新数据集

在DataAccess类中增加两个类成员变量:

     private SqlDataAdapter _customerDataAdapter; //客户数据适配器

     private SqlDataAdapter _orderDataAdapter; //订单数据适配器

 

customerDataAdapter在构造函数中的初始化为

//实例化_customerDataAdapter

SqlCommand selectCustomerComm = new SqlCommand("GetCustomer",_conn);

selectCustomerComm.CommandType = CommandType.StoredProcedure;

selectCustomerComm.Parameters.Add("@CustomerID",SqlDbType.NChar,5,"CustomerID");

        

SqlCommand insertCustomerComm = new SqlCommand("AddCustomer",_conn);

insertCustomerComm.CommandType = CommandType.StoredProcedure;

insertCustomerComm.Parameters.Add("@CustomerID",SqlDbType.NChar,5,"CustomerID");

insertCustomerComm.Parameters.Add("@CompanyName",SqlDbType.NVarChar,40,"CompanyName");

insertCustomerComm.Parameters.Add("@ContactName",SqlDbType.NVarChar,30,"ContactName");

 

SqlCommand updateCustomerComm = new SqlCommand("UpdateCustomer",_conn);

updateCustomerComm.CommandType = CommandType.StoredProcedure;

updateCustomerComm.Parameters.Add("@CustomerID",SqlDbType.NChar,5,"CustomerID");

updateCustomerComm.Parameters.Add("@CompanyName",SqlDbType.NVarChar,40,"CompanyName");

updateCustomerComm.Parameters.Add("@ContactName",SqlDbType.NVarChar,30,"ContactName");

             

SqlCommand deleteCustomerComm = new SqlCommand("DeleteCustomer",_conn);

deleteCustomerComm.CommandType = CommandType.StoredProcedure;

deleteCustomerComm.Parameters.Add("@CustomerID",SqlDbType.NChar,5,"CustomerID");

 

_customerDataAdapter = new SqlDataAdapter(selectCustomerComm);

_customerDataAdapter.InsertCommand = insertCustomerComm;

_customerDataAdapter.UpdateCommand = updateCustomerComm;

_customerDataAdapter.DeleteCommand = deleteCustomerComm;

 

上面的代码完全可以用设计器生成,觉得有些东西自己写感觉更好,不过代码还是很多。

对于_orderDataAdapter的初始化同上面的差不多,这里我们只看订单增加的处理,下面是存储过程:

CREATE PROCEDURE  AddOrder

(

     @OrderID INT OUT,

     @CustomerID NCHAR(5),

     @OrderDate DATETIME

)

AS

INSERT INTO Orders

(

     CustomerID ,

     OrderDate

)

VALUES

(

     @CustomerID ,

     @OrderDate

)

--SELECT @OrderID = @@IDENTITY  //使用触发器有可能出现问题

SET @OrderID = SCOPE_IDENTITY()

GO

 

OrderID自动增长值的获取通过输出参数来完成,这个相当不错,如果使用SqlDataAdapter.RowUpdated事件来处理那效率会很低。

对insertOrderComm对象的定义为:

SqlCommand insertOrderComm = new SqlCommand("AddOrder",_conn);

insertOrderComm.CommandType = CommandType.StoredProcedure;

insertOrderComm.Parameters.Add("@OrderID",SqlDbType.Int,4,"OrderID");

insertOrderComm.Parameters["@OrderID"].Direction = ParameterDirection.Output;

insertOrderComm.Parameters.Add("@OrderDate",SqlDbType.DateTime,8,"OrderDate");

insertOrderComm.Parameters.Add("@CustomerID",SqlDbType.NChar,5,"CustomerID");

 

在实现数据的更新方法之前我们先来明确一些更新逻辑:

对于标记为删除的行,先删除订单表的数据,再删除客户表的数据;

对于标记为添加的行,先添加客户表的数据,再添加订单表的数据。

 

(1)实现用获取修改过的DataSet的副本子集来更新数据的方法。

这也是调用Xml Web Service更新数据的常用方法,先来看第一个版本,子集的获取通过DataSet.GetChangs方法来完成。

//使用数据集子集更新数据

public void UpdateCustomerOrders(DatasetOrders ds)

{            

     DataSet dsModified = ds.GetChanges(DataRowState.Modified);//获取修改过的行

     DataSet dsDeleted = ds.GetChanges(DataRowState.Deleted);//获取标记为删除的行

     DataSet dsAdded = ds.GetChanges(DataRowState.Added);//获取增加的行

     try

     {   

         _conn.Open();//先添加客户表数据,再添加订单表数据

         if(dsAdded != null)

         {

              _customerDataAdapter.Update(dsAdded,"Customers");

              _orderDataAdapter.Update(dsAdded,"Orders");

              ds.Merge(dsAdded);

         }

         if(dsModified != null)//更新数据表

         {

              _customerDataAdapter.Update(dsModified,"Customers");

              _orderDataAdapter.Update(dsModified,"Orders");

              ds.Merge(dsModified);

         }

         if(dsDeleted != null)//先删除订单表数据,再删除客户表数据

         {

              _orderDataAdapter.Update(dsDeleted,"Orders");

              _customerDataAdapter.Update(dsDeleted,"Customers");

              ds.Merge(dsDeleted);

         }                 

     }

     catch(Exception ex)

     {

         throw new Exception("更新数据出错",ex);

     }

     finally

     {

         if(_conn.State != ConnectionState.Closed)

              _conn.Close();

     }

}

上面的方法看上去比较清晰,不过效率不会很高,至少中间创建了三个DataSet,然后又进行了多次合并。

(2)另一方法就是引用更新,不创建副本。

相对来说性能会高许多,但是如果用在Web服务上传输的数据量会更大(可以结合两个方法进行改进)。具体的实现就是通过DataTable.Select方法选择行状态来实现。

//引用方式更新数据

public void UpdateCustomerOrders(DataSet ds)

{

     try

     {   

         _conn.Open();

         //先添加客户表数据,再添加订单表数据      _customerDataAdapter.Update(ds.Tables["Customers"].Select("","",DataViewRowState.Added));

     _orderDataAdapter.Update(ds.Tables["Orders"].Select("","",DataViewRowState.Added));

     //更新数据表

     _customerDataAdapter.Update(ds.Tables["Customers"].Select("","",DataViewRowState.ModifiedCurrent));

     _orderDataAdapter.Update(ds.Tables["Orders"].Select("","",DataViewRowState.ModifiedCurrent));

//先删除订单表数据,再删除客户表数据

     _orderDataAdapter.Update(ds.Tables["Orders"].Select("","",DataViewRowState.Deleted));

     _customerDataAdapter.Update(ds.Tables["Customers"].Select("","",DataViewRowState.Deleted));           

     }

     catch(Exception ex)

     {

         throw new Exception("更新数据出错",ex);

     }

     finally

     {

         if(_conn.State != ConnectionState.Closed)

              _conn.Close();

     }

}

结合上面的两个方法我们可想到调用Web Service有更合理的方法来完成。

(3)使用事务

public void UpdateCustomerOrdersWithTransaction(DataSet ds)

{

     SqlTransaction trans = null;

     try

     {   

         _conn.Open();

         trans = _conn.BeginTransaction();

         _customerDataAdapter.DeleteCommand.Transaction = trans;

         _customerDataAdapter.InsertCommand.Transaction = trans;

         _customerDataAdapter.UpdateCommand.Transaction = trans;

         _orderDataAdapter.DeleteCommand.Transaction = trans;

         _orderDataAdapter.InsertCommand.Transaction = trans;

         _orderDataAdapter.UpdateCommand.Transaction = trans;

     _customerDataAdapter.Update(ds.Tables["Customers"].Select("","",DataViewRowState.Added));

                   _orderDataAdapter.Update(ds.Tables["Orders"].Select("","",DataViewRowState.Added));

     _customerDataAdapter.Update(ds.Tables["Customers"].Select("","",DataViewRowState.ModifiedCurrent));

     _orderDataAdapter.Update(ds.Tables["Orders"].Select("","",DataViewRowState.ModifiedCurrent));

     _orderDataAdapter.Update(ds.Tables["Orders"].Select("","",DataViewRowState.Deleted));

     _customerDataAdapter.Update(ds.Tables["Customers"].Select("","",DataViewRowState.Deleted)); 

          trans.Commit();

     }

     catch(Exception ex)

     {

         trans.Rollback();

         throw new Exception("更新数据出错",ex);

     }

     finally

     {

         if(_conn.State != ConnectionState.Closed)

              _conn.Close();

     }

}

最后让我们来看看窗体的按钮更新事件的代码:

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

{

              //提交编辑数据

     this.BindingContext[this._ds].EndCurrentEdit();

    

     if(radioButtonRef.Checked == true)//引用方式更新

         _dataAccess.UpdateCustomerOrders((DataSet)_ds);

     else if(radioButtonTrans.Checked == true)//启用事务更新数据表

         _dataAccess.UpdateCustomerOrdersWithTransaction((DataSet)_ds);

     else

     {

         DatasetOrders changedData =  (DatasetOrders)_ds.GetChanges();

         if(radioButtonWeb.Checked == true)//Web服务的更正更新

         {                     

              _dataAccess.UpdateCustomerOrders((DataSet)changedData);

         }

         else//创建副本合并方式更新

         {                 

              _dataAccess.UpdateCustomerOrders(changedData);

         }

         //去除订单表中添加的虚拟行

         foreach(DataRow row in _ds.Orders.Select("","",DataViewRowState.Added))

              _ds.Orders.RemoveOrdersRow((DatasetOrders.OrdersRow)row);

         //去除客户表中添加的虚拟行

         foreach(DataRow row in _ds.Customers.Select("","",DataViewRowState.Added))

              _ds.Customers.RemoveCustomersRow((DatasetOrders.CustomersRow)row);

         _ds.Merge(changedData);

     }

     //提交数据集状态

     _ds.AcceptChanges();

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值