DataAdapter對象可用於執行數據庫的命令操作,含有四個不同的操作命令,分別如下:
- SelectCommand:用來選取數據源中的記錄:
- InsertCommand:用來向數據源中新插入一條記錄:
- UpdateCommand:用來更新數據源中的數據:
- DeleteCommand:用來刪除數據源中的記錄
實例:
更新數據源DataAdapter的update方法可用來將dataset中的更改解析回數據源
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace DataAdapter { class Program { public static void outvalus(DataSet ds) { foreach (DataTable outtb in ds.Tables) { foreach (DataRow outrow in outtb.Rows) { foreach (DataColumn outcl in outtb.Columns) { Console.Write(outrow[outcl] + "\t"); } Console.WriteLine(); } } } static void Main(string[] args) { string constr = "server=192.168.100.222;user=sa;pwd=p@ssw1rd;database=pwd1"; SqlConnection mycon = new SqlConnection(constr); try { mycon.Open(); SqlDataAdapter my = new SqlDataAdapter("select * from book", mycon); //離線訪問數據集dataset需要用到DataAdapter 它起到一個適配的作用 //(比如電腦的適配器 把交流電適配成直流的) DataSet ds = new DataSet(); //創建數據集 my.Fill(ds, "book"); //DataAdapter填充方法 把數據庫原表填充到DataSet數據集中 Console.WriteLine("修改前的數據"); foreach (DataTable outtable in ds.Tables) { foreach (DataColumn outcolu in outtable.Columns) { Console.Write(outcolu.ColumnName + "\t\t"); //輸出DataSet中列的名稱 } Console.WriteLine(); } outvalus(ds); Console.WriteLine("修改后的數據"); foreach (DataTable outtable in ds.Tables) { foreach (DataColumn outcolu in outtable.Columns) { Console.Write(outcolu.ColumnName + "\t\t"); //輸出DataSet中列的名稱 } Console.WriteLine(); } string sqlupdate = "update book set shuoming='K3賬套備份' where bid=10001 ";//聲明一個更新的字符串 my.UpdateCommand = new SqlCommand(sqlupdate,mycon); //利用dataadapter適配中的updatecommand屬性來獲取SqlCommand(更新字符串,數據庫連接) DataRow row = ds.Tables[0].Rows[0]; //定義一個datarow row=dataset中第一個表第一行; row["shuoming"]="K3賬套備份"; //行shuoming列=k3賬套備份; my.Update(ds, "book"); //dataadapter中update方法來更新數據集中的book數據源 outvalus(ds); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } finally { mycon.Close(); } Console.ReadKey(); } } }