本文將逐步告訴您,如何取得含有資料 (從資料庫載入) 的
DataSet、修改該資料,然後將它傳回資料庫以更新原始來源。
DataSet 物件是 Microsoft .NET Framework
中資料存取的主要部分,是一種可以保存資料表、檢視和關聯性的記憶體內部物件。
需求
下面清單列出了建議使用的硬體、軟體、網路基礎架構以及所需要的 Service Pack:
- Microsoft Windows Server 2003、Microsoft Windows 2000
Professional、Microsoft Windows 2000 Server、Microsoft Windows 2000 Advanced
Server 或 Microsoft Windows NT 4.0 Server
- 已安裝 PUBS 範例資料庫的 Microsoft SQL Server 7.0 版、Microsoft SQL
Server 2000 或 Microsoft Data Engine (MSDE)
- Microsoft Visual Studio 2005 或 Microsoft Visual Studio
.NET
本文假設您已熟悉下列主題:
如何從 DataSet 物件更新資料庫
本節將示範如何使用
DataSet 物件更新資料庫中的資料。重要的是要記住,您也可以使用
SqlCommand 物件,直接插入、更新和刪除資料庫中的資料。
為了幫助您瞭解本文,請按一下下面的文件編號,檢視「Microsoft 知識庫」中的文件:
314145?
(http://support.microsoft.com/kb/314145/
)
How To Populate a DataSet Object from a Database by Using Visual C# .NET
314145?
(http://support.microsoft.com/kb/314145/
)
中涵蓋了一些主題,包括如何從資料庫擷取資料然後放入
DataSet,以及如何區隔
DataSet 與資料庫。
在載入
DataSet 之後,您就可以修改資料。
DataSet 會追蹤這些變更。
DataSet 物件可視為是從資料庫擷取的資料的記憶體內部快取。
DataSet 物件是由資料表、關聯性和條件約束集合所組成的。
如果要更新
DataSet,並將這些更新傳回資料庫,請依照下列步驟執行:
- 啟動 Visual Studio 2005 或 Visual Studio .NET。
- 在 Visual C# 中建立新的主控台應用程式。根據預設,Visual Studio 會建立靜態類別以及空的 Main() 程序。
- 請確定專案含有 System 和 System.Data 命名空間的參照。請對 System、System.Data 和 System.Data.SqlClient 命名空間使用 using 陳述式,如此您就不必在後面的程式碼中限定這些命名空間的宣告。您必須先使用這些陳述式,才能進行任何其他宣告。
using System;
using System.Data;
using System.Data.SqlClient;
- 您必須先將資訊載入 DataSet 中,才可以修改資料並將變更傳送回資料庫。如需詳細的程序,請參閱
314145?
(http://support.microsoft.com/kb/314145/
)
。為了避免重複,我們就不再詳細列出這個步驟中的程式碼。
下列程式碼中的連線字串會指向位於本機電腦上的 SQL Server (或者是執行該程式碼的電腦)。簡單的說就是會建立連線,然後建立用於在 DataSet 中填入資料的資料配接器。
注意 您必須將 User ID <username> 和 password<strong password>
變更為正確的值,才能執行這個程式碼。請確認 User ID 具有適當的權限,可以在資料庫上執行此操作。
string sConnectionString;
// Modify the following string to correctly connect to your SQL Server.
sConnectionString = "Password=<strong password>;User ID=<username>;"
+ "Initial Catalog=pubs;"
+ "Data Source=(local)";
SqlConnection objConn
= new SqlConnection(sConnectionString);
objConn.Open();
// Create an instance of a DataAdapter.
SqlDataAdapter daAuthors
= new SqlDataAdapter("Select * From Authors", objConn);
// Create an instance of a DataSet, and retrieve data from the Authors table.
DataSet dsPubs = new DataSet("Pubs");
daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors");
daAuthors.Fill(dsPubs,"Authors");
- 現在資料已經載入,您可以進行修改了。有許多方法可以加入資料列 (或記錄)。此程式碼範例使用了包含三個步驟的程序:
- 從 DataTable 取得新的 DataRow 物件。
- 依需要設定 DataRow 欄位值。
- 將該新物件傳入 DataTable.Rows 集合的 Add 方法中。
請在步驟 4 中的程式碼之後貼上下列程式碼:
//****************
// BEGIN ADD CODE
// Create a new instance of a DataTable.
DataTable tblAuthors;
tblAuthors = dsPubs.Tables["Authors"];
DataRow drCurrent;
// Obtain a new DataRow object from the DataTable.
drCurrent = tblAuthors.NewRow();
// Set the DataRow field values as necessary.
drCurrent["au_id"] = "993-21-3427";
drCurrent["au_fname"] = "George";
drCurrent["au_lname"] = "Johnson";
drCurrent["phone"] = "800 226-0752";
drCurrent["address"] = "1956 Arlington Pl.";
drCurrent["city"] = "Winnipeg";
drCurrent["state"] = "MB";
drCurrent["contract"] = 1;
// Pass that new object into the Add method of the DataTable.
tblAuthors.Rows.Add(drCurrent);
Console.WriteLine("Add was successful, Click any key to continue!!");
Console.ReadLine();
// END ADD CODE
- 如果要編輯現有的資料列,先取得適當的 DataRow 物件,然後為一或多個資料行提供新的值。您必須先找到正確的資料列,這個部分比較簡單,因為您已經載入了資料表的結構描述和資料 (步驟
4 中對 FillSchema 的呼叫)。結構描述就位之後,資料表就知道哪一個資料行是主索引鍵,也可以使用 Rows 集合中的 Find 方法了。
Find 方法會傳回在主索引鍵中有特定值的 DataRow 物件 (在這個例子中是 au_id)。有了該 DataRow 之後,就可以修改資料行。您不需要將修改包裝於 BeginEdit 和 EndEdit 中,但這樣可以簡化 DataSet 必須執行的工作,而且允許 DataSet 在呼叫 EndEdit 的同時可以執行驗證檢查。請在 ADD 程式碼之後貼上下列程式碼:
//*****************
// BEGIN EDIT CODE
drCurrent = tblAuthors.Rows.Find("213-46-8915");
drCurrent.BeginEdit();
drCurrent["phone"] = "342" + drCurrent["phone"].ToString().Substring(3);
drCurrent.EndEdit();
Console.WriteLine("Record edited successfully, Click any key to continue!!");
Console.ReadLine();
// END EDIT CODE
- 如果要使用所有這些變更來更新原始資料庫,請將 DataSet 傳入 DataAdapter 物件的 Update 方法中。
然而,您必須先設定 DataAdapter 物件的 InsertCommand、UpdateCommand 和 DeleteCommand 屬性,才可以呼叫 Update。雖然您可以手動撰寫 SQL,並使用對應的 SqlCommand 物件來產生這三個屬性,但是您也可以使用 Visual Studio .NET 自動產生這三個命令。
如果要在有需要時產生所需的命令,您必須建立 SqlCommandBuilder 物件的執行個體,然後在建構函式中使用 DataAdapter。如果要使用這個方法 (將在下列程式碼範例中示範),您必須有可供資料表使用的主索引鍵資訊。如果要存取主索引鍵資訊,請呼叫 FillSchema,然後將 DataAdapter 的 MissingSchemaAction 屬性設定為 AddWithKey,或是在程式碼中手動設定主索引鍵。請在 EDIT 程式碼之後貼上下列程式碼:
//*****************
// BEGIN SEND CHANGES TO SQL SERVER
SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors);
daAuthors.Update(dsPubs, "Authors");
Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
Console.ReadLine();
// END SEND CHANGES TO SQL SERVER
- 如果要完全刪除資料列,請使用 DataRow 物件的 Delete 方法。請注意,Rows 集合包含兩個方法:Remove 和 RemoveAt,它們看起來是刪除資料列,但實際上只是將資料列從集合中移除。只有 Delete 方法會將您的刪除傳回來源資料庫。請在 SEND CHANGES TO SQL SERVER 程式碼之後貼上下列程式碼:
//*****************
//BEGIN DELETE CODE
drCurrent = tblAuthors.Rows.Find("993-21-3427");
drCurrent.Delete();
Console.WriteLine("Record deleted successfully, Click any key to continue!!");
Console.ReadLine();
//END DELETE CODE
- 將變更傳送至 SQL Server,以移除您稍早所加入的記錄。請在 DELETE 程式碼之後貼上下列程式碼:
//*****************
// CLEAN UP SQL SERVER
daAuthors.Update(dsPubs, "Authors");
Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
Console.ReadLine();
- 儲存專案。
- 在 [偵錯] 功能表上,按一下 [開始] 以執行專案。您會注意到出現數個訊息方塊,指出程式碼的進度,並讓您可以隨著程式碼的進度查看資料的目前狀態。
完整的程式碼清單
using System;
using System.Data;
using System.Data.SqlClient;
namespace PopulateDataSet
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
string sConnectionString;
// Modify the following string to correctly connect to your SQL Server.
sConnectionString = "Password=;User ID=sa;"
+ "Initial Catalog=pubs;"
+ "Data Source=(local)";
SqlConnection objConn
= new SqlConnection(sConnectionString);
objConn.Open();
// Create an instance of a DataAdapter.
SqlDataAdapter daAuthors
= new SqlDataAdapter("Select * From Authors", objConn);
// Create an instance of a DataSet, and retrieve
// data from the Authors table.
DataSet dsPubs = new DataSet("Pubs");
daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors");
daAuthors.Fill(dsPubs,"Authors");
//****************
// BEGIN ADD CODE
// Create a new instance of a DataTable.
DataTable tblAuthors;
tblAuthors = dsPubs.Tables["Authors"];
DataRow drCurrent;
// Obtain a new DataRow object from the DataTable.
drCurrent = tblAuthors.NewRow();
// Set the DataRow field values as necessary.
drCurrent["au_id"] = "993-21-3427";
drCurrent["au_fname"] = "George";
drCurrent["au_lname"] = "Johnson";
drCurrent["phone"] = "800 226-0752";
drCurrent["address"] = "1956 Arlington Pl.";
drCurrent["city"] = "Winnipeg";
drCurrent["state"] = "MB";
drCurrent["contract"] = 1;
// Pass that new object into the Add method of the DataTable.
tblAuthors.Rows.Add(drCurrent);
Console.WriteLine("Add was successful, Click any key to continue!!");
Console.ReadLine();
// END ADD CODE
//*****************
// BEGIN EDIT CODE
drCurrent = tblAuthors.Rows.Find("213-46-8915");
drCurrent.BeginEdit();
drCurrent["phone"] = "342" + drCurrent["phone"].ToString().Substring(3);
drCurrent.EndEdit();
Console.WriteLine("Record edited successfully, Click any key to continue!!");
Console.ReadLine();
// END EDIT CODE
//*****************
// BEGIN SEND CHANGES TO SQL SERVER
SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors);
daAuthors.Update(dsPubs, "Authors");
Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
Console.ReadLine();
// END SEND CHANGES TO SQL SERVER
//*****************
//BEGIN DELETE CODE
drCurrent = tblAuthors.Rows.Find("993-21-3427");
drCurrent.Delete();
Console.WriteLine("SRecord deleted successfully, Click any key to continue!!");
Console.ReadLine();
//END DELETE CODE
//*****************
// CLEAN UP SQL SERVER
daAuthors.Update(dsPubs, "Authors");
Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
Console.ReadLine();
}
}
}
如需有關使用 ADO.NET、
DataSet 物件和 SQL 的詳細資訊,請造訪下列 Microsoft 網站: