如果要更新 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 方法中。
//**************** // 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();
}
}
}












Recommend to Front page
未分類(1)
Comment Permissions: Allow commenting