码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2017-11-14 19:31:40      阅读:284      评论:0      收藏:0      [点我收藏+]

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

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.   
  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   

原文地址:http://www.cnblogs.com/LuoEast/p/7833897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!