当前位置:Gxlcms > 数据库问题 > 对DataTable(或者DataSet)修改后,提交修改到数据库

对DataTable(或者DataSet)修改后,提交修改到数据库

时间:2021-07-01 10:21:17 帮助过:46人阅读

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

对DataTable(或者DataSet)修改后,提交修改到数据库

标签:try   bar   state   ref   ade   csharp   comment   board   new   

人气教程排行