1. 程式人生 > >對DataTable(或者DataSet)修改後,提交修改到數據庫

對DataTable(或者DataSet)修改後,提交修改到數據庫

key -h -c accept exc string itl 數據 fill

http://blog.csdn.net/nidexuanzhe/article/details/8228832

說明:通常我們在做數據庫交互時,並不一定要使用特定的SQL語句來更新數據,.NET Framwork為我們提供了自動更新的功能

[csharp] view plain copy
  1. public static void UpdateTable()
  2. {
  3. SqlConnection conn = null;
  4. string sql = "select *From Course";
  5. DataTable dt = null;
  6. DataSet ds = new DataSet();
  7. try
  8. {
  9. conn = new SqlConnection(connectionString);
  10. SqlDataAdapter sda = new SqlDataAdapter();
  11. sda.SelectCommand = new SqlCommand(sql, conn);
  12. SqlCommandBuilder cb = new SqlCommandBuilder(sda);//自動生成相應的命令,這句很重要
  13. conn.Open();
  14. sda.Fill(ds);
  15. dt = ds.Tables[0];
  16. DataRow dr = dt.NewRow();
  17. dr["ID"] = 1006;
  18. dr["Name"] = "面向對象編程";
  19. dr["Grade"] = "10004";
  20. dt.Rows.Add(dr);
  21. sda.Update(dt);//對表的更新提交到數據庫
  22. //DataRow[] drs = dt.Select(null, null, DataViewRowState.Added);//或者搜索之後再更新
  23. //sda.Update(drs);
  24. dt.AcceptChanges();
  25. }
  26. catch (SqlException ex)
  27. { }
  28. finally
  29. {
  30. conn.Close();
  31. }
  32. }

對DataTable(或者DataSet)修改後,提交修改到數據庫