有關DataAdapter對象的說明

來源:互聯網
上載者:User

       DataAdapter對象和Connection對象、Command對象、DataReader對象一起時構成ADO.NET的四個重要對象之一。

       DataAdapter對象在資料集(DataSet)和資料來源(DataSource)之間串連中起著橋樑的作用。下面就利用DataAdapter對象來對資料來源中的資料進行操作,包括添加、修改和刪除操作。

(1)、添加資料

       假如有一個Users表,其中包括如下欄位:ID,UserName,Password,現在利用DataAdapter對象的Update方法來向資料來源中增加一條資料。

      .......

      using System.Data.SqlClient;

      .......

      SqlConnection con = new SqlConnection("資料庫連接字串");

      con.Open();

      SqlDataAdapter da = new SqlDataAdapter("select * from Users",con);

      SqlCommandBuilder scb = new SqlCommandBuilder(da);

      DataSet ds = new DataSet();

      da.Fill(ds,"user");

      DataRow dr = ds.Tables["user"].NewRow();

      dr["ID"] = "05205020229";

      dr["UserName"] = "暖楓無敵";

      dr["Password"] = "admin";

      ds.Tables["user"].Rows.Add(dr);

      da.Update(ds,"user");

      ..........

      在資料來源中的表中新增加一行,然後給每個欄位賦值,將該行添加到表中,最後利用資料配接器(DataAdapter)更新資料集(DataSet),

將資料表的變化,更新到資料來源中去。

(2)、修改資料

       接著上面的內容,假如想將新增加的Password欄位值更改為admin888的話,該如何操作呢?步驟如下:

      .......

      using System.Data.SqlClient;

      .......

      SqlConnection con = new SqlConnection("資料庫連接字串");

      con.Open();

      SqlDataAdapter da = new SqlDataAdapter("select * from Users",con);

      SqlCommandBuilder scb = new SqlCommandBuilder(da);

      DataSet ds = new DataSet();

      da.Fill(ds,"user");

      DataRow dr = ds.Tables["user"].Select("ID='05205020229' ");

      dr[0]["Password"] = "admin888";

      da.Update(ds,"user");

      ..........

 

(3)、刪除資料

       如果要刪除上面的一條記錄,代碼如下:

       .......

      using System.Data.SqlClient;

      .......

      SqlConnection con = new SqlConnection("資料庫連接字串");

      con.Open();

      SqlDataAdapter da = new SqlDataAdapter("select * from Users",con);

      SqlCommandBuilder scb = new SqlCommandBuilder(da);

      DataSet ds = new DataSet();

      da.Fill(ds,"user");

      DataRow dr = ds.Tables["user"].Select("ID='05205020229' ");

      dr[0].Delete();

      da.Update(ds,"user");

      ..........

 

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.