標籤:style blog java color 使用 os
1.首先從資料庫獲得資料填充到DataSet類,該類中的表和資料庫中的表相互映射。
2.對DataSet類中的表進行修改(插入,更新,刪除等)
3.同步到資料庫中:使用SqlDataAdapter執行個體名.Update(DataSet執行個體名,DataSet中和資料庫中表相映射的表名),它必須和SqlCommandBuilder必須組合使用
SqlCommandBuilder:自動產生單表命令,用於將對 DataSet 所做的更改與關聯的 SQL Server 資料庫的更改相協調,意思是對資料庫執行產生相應的sql語句,用於更新資料庫
Update()方法:執行剛才自動產生的命令
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data;using System.Data.SqlClient;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { string source = "server=(local) \\SQLEXPRESS;integrated security=true;database=student"; SqlConnection con = new SqlConnection(source); con.Open(); if (con.State == ConnectionState.Open) Console.WriteLine("資料庫已串連!"); SqlDataAdapter sda = new SqlDataAdapter();//定義資料配接器 DataSet ds = new DataSet(); //通過資料配接器對資料庫進行查詢 string select = "select * from class"; SqlCommand com1 = new SqlCommand(select, con);//定義一個查詢命令 sda.SelectCommand = com1;//使用sda.SelectCommand執行這個查詢命令(在資料來源中選擇記錄) sda.Fill(ds, "result");//將查詢結果填充到DataSet類中,並命名為selectresult //顯示查詢結果 foreach (DataRow x in ds.Tables["result"].Rows) Console.WriteLine("name:{0} id:{1}", x[0], x[1]); //添加新的行到DataSet中的DataTable中(第一種方式): //使用NewRow()方法,返回一個空白行,然後填充資料,最後把它添加到Rows集合中 DataRow r = ds.Tables["result"].NewRow(); r["name"] = "資料結構"; r["id"] = 3; ds.Tables["result"].Rows.Add(r);//添加新的行到DataSet中的DataTable中(第二種方式): //把一組已經初始化的數組傳遞到Row.Add()方法 ds.Tables["result"].Rows.Add(new object[] { "java",4}); //刪除特定的一行 for(int i=0;i<ds.Tables["result"].Rows.Count;i++) { if (ds.Tables["result"].Rows[i]["name"].ToString().Trim() == "c語言")//trim():需要移除行中儲存資料的前置空白字串和尾部空白字串 { //Remove()和delete()的區別:Remove移除一行後,該行後面的行全部自動向前移,而Delete不向前移,但是使用delete無法更新到資料庫,因為無法產生sql的刪除代碼 //ds.Tables["result"].Rows.Remove(ds.Tables["result"].Rows[i]); //i--; ds.Tables["result"].Rows[i].Delete();//移除一行的另一種方式 } } SqlCommandBuilder scb = new SqlCommandBuilder(sda);//自動產生單表命令,用於將對 DataSet 所做的更改與關聯的 SQL Server 資料庫的更改相協調,意思是對資料庫執行產生相應的sql語句,用於更新資料庫 sda.Update(ds, "result");//和SqlCommandBuilder必須組合使用,執行剛才自動產生的命令,“result”為DataSet和資料庫中互相映射的表,意思是把result表中所做的更改同步到資料庫源表中 foreach (DataRow x in ds.Tables["result"].Rows) Console.WriteLine("name:{0} id:{1}", x[0], x[1]); } }}