對DataTable(或者DataSet)修改後,提交修改到數據庫
阿新 • • 發佈:2017-11-14
key -h -c accept exc string itl 數據 fill
http://blog.csdn.net/nidexuanzhe/article/details/8228832
說明:通常我們在做數據庫交互時,並不一定要使用特定的SQL語句來更新數據,.NET Framwork為我們提供了自動更新的功能
[csharp] view plain copy- public static void UpdateTable()
- {
- SqlConnection conn = null;
- string sql = "select *From Course";
- DataTable dt = null;
- DataSet ds = new DataSet();
- try
- {
- conn = new SqlConnection(connectionString);
- SqlDataAdapter sda = new SqlDataAdapter();
- sda.SelectCommand = new SqlCommand(sql, conn);
- SqlCommandBuilder cb = new SqlCommandBuilder(sda);//自動生成相應的命令,這句很重要
- conn.Open();
- sda.Fill(ds);
- dt = ds.Tables[0];
- DataRow dr = dt.NewRow();
- dr["ID"] = 1006;
- dr["Name"] = "面向對象編程";
- dr["Grade"] = "10004";
- dt.Rows.Add(dr);
- sda.Update(dt);//對表的更新提交到數據庫
- //DataRow[] drs = dt.Select(null, null, DataViewRowState.Added);//或者搜索之後再更新
- //sda.Update(drs);
- dt.AcceptChanges();
- }
- catch (SqlException ex)
- { }
- finally
- {
- conn.Close();
- }
- }
對DataTable(或者DataSet)修改後,提交修改到數據庫