下面根據(jù)我的一些經(jīng)驗來舉例說明在ADO.NET中的多表填充、關(guān)聯(lián)表更新以及多個Command對象執(zhí)行過程中啟用事務(wù)的操作。歡迎大家交流,或在Blog上留言。

創(chuàng)新互聯(lián)服務(wù)項目包括北戴河網(wǎng)站建設(shè)、北戴河網(wǎng)站制作、北戴河網(wǎng)頁制作以及北戴河網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,北戴河網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到北戴河省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
一、準(zhǔn)備工作
對于NorthWind數(shù)據(jù)庫大家都比較熟悉,所以這里拿它為例,我把Customers(客戶表)、Orders(訂單表)、Order Details(訂單詳細(xì)表)合起來建立了一個類型化的數(shù)據(jù)集,類型名稱為DatasetOrders,每個表只包括一些字段,下面是在Visual Studio .NET中建立的一個截圖:
上面建立了兩個關(guān)系表示為Customers —> Orders —>Order Details。因為Orders表的OrderID字段為自動增長列,這里把就把它的AutoIncrementSeed和AutoIncrementStep值設(shè)置成了-1,這在實際添加訂單的過程中可能會比較明顯,不過不設(shè)也沒問題
二.填充數(shù)據(jù)集
建立一個窗體程序來演示實際的操作,界面如下:
整個應(yīng)用程序就是一個Form,上面的三個DataGrid分別用來顯示相關(guān)表的數(shù)據(jù),不過他們是互動的。另外的兩個單選框用來決定更新數(shù)據(jù)的方式,兩個按鈕正如他們的名稱來完成相應(yīng)的功能。
這里我們用一個DataAdapter來完成數(shù)據(jù)集的填充,執(zhí)行的存儲過程如下:
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
|
為了減少數(shù)據(jù)量,這里只取了CustomerID以’A’開頭的數(shù)據(jù)。建立DataAccess類來管理窗體同數(shù)據(jù)層的交互:
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; ///構(gòu)造函數(shù) public DataAccess() { _conn = new SqlConnection(_connstring); }
|
下面的函數(shù)完成單個數(shù)據(jù)適配器來完成數(shù)據(jù)集的填充,
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這個方法超過兩個表的填充時會出現(xiàn)錯誤,其實里面的邏輯是錯的,只不過兩個表的時候剛好湊巧,下面是從里面截的代碼:
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();//這里出現(xiàn)錯誤
} } 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; //…… //構(gòu)造函數(shù) public Form1() { InitializeComponent(); _dataAccess = new DataAccess(); _ds = new DatasetOrders(); _ds.EnforceConstraints = false; //關(guān)閉約束檢查,提高數(shù)據(jù)填充效率 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; }
|
對于上面的三個表的動態(tài)關(guān)聯(lián),你也可以使用SetDataBinding方法來完成數(shù)據(jù)的動態(tài)綁定,而不是分別指定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); }
|
數(shù)據(jù)填充事件處理如下:
private void buttonFillData_Click(object sender, System.EventArgs e) { _ds.Clear();//重新填充數(shù)據(jù)集 _dataAccess.FillCustomerOrdersInfo(_ds); //_dataAccess.FillCustomerOrdersInfoWithSqlHelper(_ds); }
|
執(zhí)行上面的事件處理函數(shù)我們會看到數(shù)據(jù)顯示到對應(yīng)的DataGrid上,如(圖2-1)所示。
如果使用數(shù)據(jù)讀取器獲取多表紀(jì)錄下面是實現(xiàn)的。
您正在閱讀的是《ADO.NET中的多數(shù)據(jù)表操作讀取》
【編輯推薦】
- ADO.NET數(shù)據(jù)庫連接、操作SQL舉例
- 詳解ADO.NET客戶端開發(fā)數(shù)據(jù)驅(qū)動的應(yīng)用程序
- 使用LINQ和ADO.NET創(chuàng)建Silverlight程序
本文題目:ADO.NET中的多數(shù)據(jù)表操作讀取
標(biāo)題路徑:
http://www.dlmjj.cn/article/cdpjdsc.html