天天看點

SqlDataAdapter的用法

SqlDataAdapter是DataSet和 資料庫的連接配接(橋接器),用于檢索和儲存資料,SqlDataAdaoter通過對資料源使用适當的Transact-SQL語句映射File(他作為填充DataSet的資料源中的資料)和Update(更改DataSet中的資料源)提供一種橋接方式,當SqlDataAdapter填充DataSet時,他為傳回的資料建立必須的表和列

第一種方式(字元串查詢)

string strCon =“uid=sa;pwd=123456;database=test;server=127.0.0.1”;

sql = “select * from table”;

SqlDataAdapter da = new SqlDataAdapter(sql,strCon);

DataSet ds = new DataSet();

da.Fill(ds,“臨時虛拟表”);

dataGridView1.DataSource= ds.Tables[“臨時虛拟表”];

第二種方式使用SqlConneclion對象來建立

string strConn=“uid=賬号;pwd=密碼;database=資料庫;server=伺服器”;//SQL Server連結字元串

SqlConnection conn=new SqlConnection(strConn);

string strSql=“SELECT * FROM 表名”;

SqlDataAdapter da = new SqlDataAdapter(strSql, conn);

DataSet ds=new DataSet();//建立DataSet執行個體

da.Fill(ds,“自定義虛拟表名”);//使用DataAdapter的Fill方法(填充),調用SELECT指令

第三種方式通過SqlCommand對象

string strConn=“uid=賬号;pwd=密碼;database=資料庫;server=伺服器”;//SQL Server連結字元串

SqlConnection connSql=new SqlConnection (strConn); //Sql連結類的執行個體化

connSql.Open ();//打開資料庫

//使用SqlDataAdapter時沒有必要從Connection.open()打開,

//SqlDataAdapter會自動打開關閉它。

string strSql = “SELECT * FROM 表名”; //要執行的SQL語句

SqlCommand cmd = new SqlCommand(strSql, connSql);

SqlDataAdapter da=new SqlDataAdapter(cmd); //建立DataAdapter資料擴充卡執行個體

DataSet ds=new DataSet();//建立DataSet執行個體

da.Fill(ds,“自定義虛拟表名”);//使用DataAdapter的Fill方法(填充),調用SELECT指令

connSql.Close();//關閉資料庫

如果隻需要執行SQL語句或SP,就沒必要用到DataAdapter ,直接用SqlCommand的Execute系列方法就可以了。SqlDataadapter的作用是實作Dataset和DB之間的橋梁:比如将對DataSet的修改更新到資料庫。

SqlDataAdapter的UpdateCommand的執行機制是:當調用SqlDataAdapter.Update()時,檢查DataSet中的所有行,然後對每一個修改過的Row執行SqlDataAdapter.UpdateCommand ,也就是說如果未修改DataSet中的資料,SqlDataAdapter.UpdateCommand不會執行。

1、在使用Fill方式時,可以指定DataTable,而不是DataSet:

string strConn=“uid=賬号;pwd=密碼;database=資料庫;server=伺服器”;//SQL Server連結字元串

strSql=“SELECT * FROM 表名”;

SqlDataAdapter da = new SqlDataAdapter(strSql, strConn);

DataTable tbl=new DataTable( );

da.Fill(tbl);

注意打開和關閉連接配接的處理

在調用SqlCommand對象執行sql指令之前,需要保證與該對象關聯的SqlConnection對象是打開的,否則SqlCommand的方法執行時将引發一個異常,但是我們在上面的代碼中看到,SqlDataAdapter沒有這樣的要求。

如果調用SqlDataAdapter的Fill方法,并且其SelectCommand屬性的SqlConnection是關閉狀态,則SqlDataAdapter會自動打開它,然後送出查詢,擷取結果,最後關閉連接配接。如果在調用Fill方法前,SqlConnection是打開的,則查詢執行完畢後,SqlConnection還将是打開的,也就是說SqlDataAdapter會保證SqlConnection的狀态恢複到原來的情形

string strConn=“uid=賬号;pwd=密碼;database=資料庫;server=伺服器”;//SQL Server連結字元串

SqlConnection conn=new SqlConnection(strConn);

SqlDataAdapter daCustomers,daOrders;

strSql=“SELECT * FROM Customers”;

daCustomers = new SqlDataAdapter(strSql, conn);

strSql=“SELECT * FROM Orders”;

daOrders=new SqlDataAdapter(strSql, conn);

DataSet ds=new DataSet();

daCustomers.Fill(ds,“Customers”);

daOrders.Fill(ds,“Orders”);

以上代碼會導緻連接配接被打開和關閉兩次,在調用Fill方法時各一次。為了避免打開和關閉SqlConnection對象,在調用SqlDataAdapter對象的Fill方法之前,我們可以先打開SqlConnection對象,如果希望之後關閉連接配接,我們可以再調用Close方法,就像這樣: