using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace _14._15DataAdapter对象 { class Program { static void Main(string[] args) { string constr = "Server=.;uid=sa;pwd=zqyo850619;database=csharpzxw"; SqlConnection mycon = new SqlConnection(constr); try { //mycon.Open(); //string sql = "select*from mytable001"; //SqlDataAdapter myda = new SqlDataAdapter(sql, mycon);//创建SQL适配器 //DataSet myds = new DataSet();//初始化数据集 //myda.Fill(myds, "mytable001");//适配器将表填充进入DataSet //Console.WriteLine("填充成功"); //outValues(myds); //Console.ReadKey(); //更改数据源文件 mycon.Open(); string updateSql = "update mytable001 set gender='女' where name='张三'"; SqlDataAdapter myda = new SqlDataAdapter("select * from mytable001",mycon); DataSet myds = new DataSet(); myda.Fill(myds, "mytable001");//acceptchange 处于true状态 Console.WriteLine("原dataset对象内容"); outValues(myds); myda.UpdateCommand = new SqlCommand(updateSql, mycon); DataRow row = myds.Tables[0].Rows[0]; row["gender"] = "女"; Console.WriteLine("更改后dataset的内容"); myda.Update(myds, "mytable001"); outValues(myds); Console.ReadKey(); } catch(Exception ex) { Console.WriteLine(ex.Message.ToString()); } finally { mycon.Close(); } } public static void outValues(DataSet ds) { foreach(DataTable dt in ds.Tables) { Console.WriteLine(); foreach (DataRow row in dt.Rows) { foreach(DataColumn col in dt.Columns) Console.Write(row[col]+" "); } Console.WriteLine("表名" + dt.TableName); } } } }