对DataTable(或者DataSet)修改后,提交修改到数据库
http://blog.csdn.net/nidexuanzhe/article/details/8228832
说明:通常我们在做数据库交互时,并不一定要使用特定的SQL语句来更新数据,.NET Framwork为我们提供了自动更新的功能
- 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();
- }
- }