close

 詳:http://cht.gotdotnet.com/quickstart/howto/doc/adoplus/updatedatafromdb.aspx

 

// Create a new Connection and SqlDataAdapter

    SqlConnection myConnection = new SqlConnection("server=(local)\\VSdotNET;Trusted_Connection=yes;database=northwind");
    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from Customers", myConnection);
    DataSet myDataSet = new DataSet();
    DataRow myDataRow;
   
    // Create command builder. This line automatically generates the update commands for you, so you don't
    // have to provide or create your own.
    SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
   
    // Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
    // key & unique key information to be retrieved unless AddWithKey is specified.
    mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
   
    mySqlDataAdapter.Fill(myDataSet, "Customers");
   
    myDataRow = myDataSet.Tables["Customers"].NewRow();
    myDataRow["CustomerId"] = "NewID";
    myDataRow["ContactName"] = "New Name";
    myDataRow["CompanyName"] = "New Company Name";
   
    myDataSet.Tables["Customers"].Rows.Add(myDataRow);
DataTable 必須透過 NewRow 方法傳回 DataRow。該方法會以適當的 DataTable 結構描述 (Schema) 傳回 DataRow 物件。新的 DataRow 在加入 RowsCollection 之前,是不受資料表支配的。

您可以藉由存取 DataRow 來變更其中的資料。透過 Rows 屬性,您可以在 RowsCollection 中使用資料列的索引:

    DataRow myDataRow1 = myDataSet.Tables["Customers"].Rows.Find("ALFKI");
   myDataRow1["ContactName"]="Peach";

其中,「ALFKI」是「Customers」資料表的「CustomerID」主索引鍵值。使用 SqlDataAdapter 時,索引鍵是從資料庫中建立的。如果您不是透過 PrimaryKey 屬性使用資料庫的話,也可以設定索引鍵。

請使用 Delete 方法來移除資料列。請注意,一旦資料集被更新到資料庫,在資料集中發生的邏輯刪除只會導致實際刪除。您同樣也可以在資料集上使用 RejectChanges,在那樣的情況下,資料列會被還原。

    myDataSet.Tables["Customers"].Rows[0].Delete();

原始值和新值都會維持在資料列中。RowChanging 事件可以讓您存取原始值和新值,以決定是否繼續編輯。由於我們維持原始值和新值,因此可以建立開放式鎖定 (Optimistic Locking) 和索引鍵變更等案例。

在將更新送回資料庫之前,您需要設定 InsertCommandUpdateCommandDeleteCommand 來調解資料庫的變更。由於案例有限,您可以使用 SqlCommandBuilder 來自動產生適合您的案例,如下列範例所示:

    SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
 
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 11 的頭像
    11

    冠霖的部落格

    11 發表在 痞客邦 留言(0) 人氣()