該主題說明了如何使用 DataSet 在數據庫中更新數據。你依然能夠直接使用 SqlCommand 在數據庫中插入、更新、和刪除數據,記住這一點也很重要。理解「 從數據庫填充DataSet」涵蓋的概念有助於你理解這個主題。
SqlConnection myConnection = new SqlConnection("server=(local);Integrated Security=SSPI;database=northwind"); SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM Customers", myConnection); DataSet myDataSet = new DataSet(); DataRow myDataRow; // 建立命令構建器,會自動建立更新命令,沒必要手動提供或建立。 SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myDataAdapter); // 爲 MissingSchemaAction 屬性設置 AddWithKey,除非指定 AddWithKey,Fill 將不會檢索到主鍵 & 惟一鍵信息。 myDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; myDataAdapter.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); myDataAdapter.Update(myDataSet, "Customers");
myDataSet.Tables["Customers"].Rows[0]["ContactName"]="Peach";
DataRow myDataRow1 = myDataSet.Tables["Customers"].Rows.Find("ALFKI"); myDataRow1["ContactName"]="Peach";
myDataSet.Tables["Customers"].Rows[0].Delete();
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.Update(myDataSet, "Customers");