明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺!

ADO.NET中的多數(shù)據(jù)表設(shè)置淺析—讀取

[摘要]ADO.NET中的多數(shù)據(jù)表操作淺析—讀取作者:鄭佐??????? 2004-8-5???????? 在開發(fā)基于.NET平臺的數(shù)據(jù)庫應(yīng)用程序時(shí),我們一般都會用到DataSet,作為ADO.NET的核心類它為我們提供了強(qiáng)大的功能,而整個(gè)看上去就像是放在內(nèi)存內(nèi)的一個(gè)小型數(shù)據(jù)庫,內(nèi)部包括了DataTabl...
ADO.NET中的多數(shù)據(jù)表操作淺析—讀取

作者:鄭佐??????? 2004-8-5

???????? 在開發(fā)基于.NET平臺的數(shù)據(jù)庫應(yīng)用程序時(shí),我們一般都會用到DataSet,作為ADO.NET的核心類它為我們提供了強(qiáng)大的功能,而整個(gè)看上去就像是放在內(nèi)存內(nèi)的一個(gè)小型數(shù)據(jù)庫,內(nèi)部包括了DataTable、DataView、DataRow、DataColumn、Constraint以及DataRelation。當(dāng)初看到它時(shí)真的是有點(diǎn)興奮。

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

????????

一、準(zhǔn)備工作

???????? 對于NorthWind數(shù)據(jù)庫大家都比較熟悉,所以這里拿它為例,我把Customers(客戶表)、Orders(訂單表)、Order Details(訂單詳細(xì)表)合起來建立了一個(gè)類型化的數(shù)據(jù)集,類型名稱為DatasetOrders,每個(gè)表只包括一些字段,下面是在Visual Studio .NET中建立的一個(gè)截圖:

?

圖1-1

上面建立了兩個(gè)關(guān)系表示為Customers —> Orders —>Order Details。因?yàn)镺rders表的OrderID字段為自動增長列,這里把就把它的AutoIncrementSeed和AutoIncrementStep值設(shè)置成了-1,這在實(shí)際添加訂單的過程中可能會比較明顯,不過不設(shè)也沒問題。

????????

二.填充數(shù)據(jù)集

建立一個(gè)窗體程序來演示實(shí)際的操作,界面如下:



圖2-1

整個(gè)應(yīng)用程序就是一個(gè)Form,上面的三個(gè)DataGrid分別用來顯示相關(guān)表的數(shù)據(jù),不過他們是互動的。另外的兩個(gè)單選框用來決定更新數(shù)據(jù)的方式,兩個(gè)按鈕正如他們的名稱來完成相應(yīng)的功能。

這里我們用一個(gè)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ù)完成單個(gè)數(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這個(gè)方法超過兩個(gè)表的填充時(shí)會出現(xiàn)錯誤,其實(shí)里面的邏輯是錯的,只不過兩個(gè)表的時(shí)候剛好湊巧,下面是從里面截的代碼:

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;

???????? }

對于上面的三個(gè)表的動態(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ì)錄下面是實(shí)現(xiàn)的一種方式(參考):

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());//獲取數(shù)據(jù)代碼

???? }

}while(reader.NextResult());

Console.ReadLine();

_conn.Close();

?

?