ADO數(shù)據(jù)庫連接對象詳解案例(適合初學(xué)者)_第1頁
ADO數(shù)據(jù)庫連接對象詳解案例(適合初學(xué)者)_第2頁
ADO數(shù)據(jù)庫連接對象詳解案例(適合初學(xué)者)_第3頁
ADO數(shù)據(jù)庫連接對象詳解案例(適合初學(xué)者)_第4頁
ADO數(shù)據(jù)庫連接對象詳解案例(適合初學(xué)者)_第5頁
已閱讀5頁,還剩7頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

ADO.NET數(shù)據(jù)庫連接對象詳解(案例)注意:希望大家在copy代碼的時候注意命名空間的引用,因此需要加上以下語句:usingSystem.Data;usingSystem.Data.SqlClient;SqlConnetion對象:主要是連接程序和數(shù)據(jù)源的“橋梁”,要存取數(shù)據(jù)源中的數(shù)據(jù),首先要建立程序和數(shù)據(jù)源之間的連接。混合模式stringconnStr="server/DataSource=(local);uid=sa;pwd=;database/InitialCatalog=demo";SqlConnectionconn=newSqlConnection(connStr);或連起來寫:SqlConnectionconn=newSqlConnection("server=(local);uid=sa;pwd=;database=demo");使用Windows驗證方式:string connetionString="server=(local);database=demo;trusted_connetion/IntergtatedSecrity=true";SqlConnectionconn=newSqlConnection(connetionString);SqlConnetion對象實例演示:v%@ImportNamespace="System.Data"%>v%@ImportNamespace="System.Data.SqlClient"%><scriptlanguage="C#"runat="server">publicvoidPage_Load(objectsender,EventArgse){stringconnStr="server=.;database=demo;uid=sa;pwd=xushouwei";//SqlConnection conn = newSqlConnection("server=.;database=demo;uid=sa;pwd=xushouwei");SqlConnectionconn=newSqlConnection(connStr);conn.Open();Response.Write(”連接成功!");}</script>Command對象:主要用來對數(shù)據(jù)發(fā)出一些指令,通過Command對象可以對數(shù)據(jù)庫進行查詢、增加、修改、刪除以及調(diào)用數(shù)據(jù)庫中的存儲過程等操作。建立Command對象的常用語法為:SqlCommandcmd=newSqlCommand(cmdText(用于描述需要執(zhí)行的操作),myConnection(用于指定所使用的連接對象));或者這樣寫:SqlCommandcmd=myConnection.CreateCommand();cmd.CommandText=cmdText;Command對象的ExecuteNonQuery方法向用戶表中增加一條記錄實例:publicvoidPage_Load(objectsender,EventArgse){stringconnStr="server=.;uid=sa;pwd=xushouwei;database=demo";//stringconnStr=System.Configuration.ConfigurationManager.AppSettings["DSN"];〃創(chuàng)建ConnectionSqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建CommandSqlCommand cmd = new SqlCommand("insert intoUsers(UserName,RealName)values('Jasxu',徐守威')",conn);〃打開Connectionconn.Open();〃執(zhí)行Command命令cmd.ExecuteNonQuery();〃關(guān)閉Connectionconn.Close();}Command對象的ExecuteNonQuery方法向用戶表中Update(更新/修改)一條記錄實例:publicvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串connStrstringconnStr="server=.;uid=sa;pwd=xushouwei;database=demo";〃創(chuàng)建ConnectionSqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建CommandSqlCommandcmd=newSqlCommand("updateUserssetRealName='徐守威'whereUserID=1",conn);〃打開Connectionconn.Open();〃執(zhí)行Command命令cmd.ExecuteNonQuery();〃關(guān)閉Connectionconn.Close();}Command對象的ExecuteNonQuery方法向用戶表中Delete(刪除)一條記錄實例:publicvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串connStrstringconnStr="server=.;uid=sa;pwd=xushouwei;database=demo";〃創(chuàng)建ConnectionSqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建CommandSqlCommandcmd=newSqlCommand("deletefromUserswhereUserID=l",conn);〃打開Connectionconn.Open();〃執(zhí)行Command命令cmd.ExecuteNonQuery();〃關(guān)閉Connectionconn.Close();}執(zhí)行帶參數(shù)的Command實例演示:方法一:protectedvoidButton1_Click(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=.;uid=sa;pwd=xushouwei;database=demo";〃創(chuàng)建ConnectionSqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建Command,SQL語句中有一個參數(shù)@UserNameSqlCommandcmd=newSqlCommand("select*fromUserswhereRealName=@UserName",conn);〃把@UserName參數(shù)加入到Parameters,并給參數(shù)賦值cmd.Parameters.Add("@UserName",SqlDbType.VarChar).Value=TextBox1.Text;〃打開連接conn.Open();〃從數(shù)據(jù)庫取回數(shù)據(jù)到DataReaderSqlDataReaderreader=cmd.ExecuteReader();〃把SqlDataReader綁定到GridView控件dg.DataSource=reader;〃在GridView中顯示綁定數(shù)據(jù)dg.DataBind();〃關(guān)閉DataReaderreader.Close();〃關(guān)閉連接conn.Close();}方法二:protectedvoidButton1_Click(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=NIIT038;uid=sa;pwd=xushouwei;database=example";〃建立connection連接SqlConnectionconn=newSqlConnection(connStr);〃根據(jù)用戶的輸入動態(tài)創(chuàng)建sqlstringsql="select*fromUserswhereRealName='"+TextBox1.Text.Trim()+"'";〃創(chuàng)建command,其sql由用戶輸入而定SqlCommandcmd=newSqlCommand(sql,conn);〃打開連接conn.Open();〃從數(shù)據(jù)庫取回到DataReaderSqlDataReaderreader=cmd.ExecuteReader();〃把DataReader綁定到Gridviewdg.DataSource=reader;〃在Gridview中顯示數(shù)據(jù)綁定dg.DataBind();〃關(guān)閉DataReaderreader.Close();〃關(guān)閉連接conn.Close();}Command對象的ExecuteScalar方法:返回執(zhí)行結(jié)果中首行首列的值,該方法只能執(zhí)行select語句,一般用于取得最大值、最小值、平均值、記錄數(shù)。實例演示如下:protectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=NIIT038;uid=sa;pwd=xushouwei;database=example";〃建立connection連接SqlConnectionconn=newSqlConnection(connStr);〃打開連接conn.Open();〃倉U建commandSqlCommandcmd=newSqlCommand("selectcount(*)fromUsers",conn);〃執(zhí)行ExecuteScalar方法并把返回值賦給countintcount=(int)cmd.ExecuteScalar();Response.Write("User表中共有"+count+"個用戶!”);}DataReader對象:當只需要順序第讀取數(shù)據(jù)而不需要其他操作時,可以使用DataReader對象,由于DataReader在讀取數(shù)據(jù)的時候限制了每次以只讀的方式讀取一條記錄,并不允許其他的操作,所以使用DataReader不但可以節(jié)省資源而且效率很高。DataReader類是抽象類,因此不能直接實例化而是通過執(zhí)行Command對象的ExecuteReader方法返回DataReader實例。實例演示如下:protectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=NIIT038;uid=sa;pwd=xushouwei;database=example";〃建立connection連接SqlConnectionconn=newSqlConnection(connStr);〃打開連接conn.Open();〃倉U建commandSqlCommandcmd=newSqlCommand("select*fromBookShop",conn);〃從數(shù)據(jù)庫取回到DataReaderSqlDataReaderreader=cmd.ExecuteReader();〃顯示SqlDataReader對象中的所有數(shù)據(jù)while(reader.Read()){Response.Write(reader["BookName"]+"  ");Response.Write(reader["BookDescription"]+"<BR>");}〃關(guān)閉DataReaderreader.Close();〃關(guān)閉連接conn.Close();}DataSet對象:DataSet對象可以視為一個內(nèi)存數(shù)據(jù)庫,是由許多數(shù)據(jù)表(DataTable)、數(shù)據(jù)表聯(lián)系(Relation)>約束(Constraint)記錄(DataRow)以及字段(DataColumn)對象的集合所組成。DataSet對象的結(jié)構(gòu)也與數(shù)據(jù)庫相似,DataSet對象由一個或多個DataTable組成,DataTable相當于數(shù)據(jù)庫中的表,有列DataColumn與行DataRow,分別對應(yīng)于數(shù)據(jù)庫的字段與記錄。DataSet對象中的數(shù)據(jù)存放在DataTable中。DataSet對象一個重要的特征是<離線操作>(重要),即從數(shù)據(jù)庫中取回數(shù)據(jù),存到DataSet對象中后,程序可以馬上斷開與數(shù)據(jù)庫的連接,用戶可以對內(nèi)存中的DataSet中的數(shù)據(jù)進行增加、刪除、修改等操作,而當需要把改動反映到數(shù)據(jù)庫時,只要重新與數(shù)據(jù)庫建立連接,并利用相應(yīng)的命令實現(xiàn)更新。實例演示如下:protectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=NIIT038;uid=sa;pwd=xushouwei;database=example";〃建立connection連接SqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建SqlDataAdapter對象(以后會有詳解)SqlDataAdapterda=newSqlDataAdapter("select*fromUsers",conn);〃創(chuàng)建DataSet對象DataSetds=newDataSet();〃使用SqlDataAdapter的Fill方法填充DataSetda.Fill(ds,"Users");〃實現(xiàn)數(shù)據(jù)綁定dg.DataSource=ds.Tables[O];〃等同于--》dg.DataSource=ds.Tables["Users"]或者dg.DataSource=ds.Tables["Users"].DefaultView或者dg.DataSource=dsdg.DataBind();}DataTable對象:DataTable對象是構(gòu)成DataSet最主要的對象, DataTable對象是由DataColumns集合以及DataRow集合組成,DataSet的數(shù)據(jù)就存放在DataTable對象中。實例演示如下:protectedvoidPage_Load(objectsender,EventArgse){〃去BookShop表的前三條記錄到DataReader中〃創(chuàng)建連接字符串stringconnStr="server=NIIT038;uid=sa;pwd=xushouwei;database=example";〃建立connection連接SqlConnectionconn=newSqlConnection(connStr);〃打開連接conn.Open();〃倉U建commandSqlCommandcmd=newSqlCommand("selecttop3BookName,BookDescriptionfromBookShop",conn);〃從數(shù)據(jù)庫取回到DataReaderSqlDataReaderreader=cmd.ExecuteReader();〃創(chuàng)建內(nèi)存表DataTableDataTabletable=newDataTable("BookDetails");〃增加Index列table.Columns.Add("Index");〃增力口BookName歹Utable.Columns.Add("BookName");〃增加Description列Itable.Columns.Add("BookDescription");//DataReader中的數(shù)據(jù)賦給內(nèi)存表DataTableintindex=1;while(reader.Read()){〃動態(tài)創(chuàng)建表行數(shù)DataRowrow=table.NewRow();row["Index"]=index.ToString();row["BookName"]=reader["BookName"].ToString();row["BookDescription"]=reader["BookDescription"].ToString();table.Rows.Add(row);index=index+1;〃關(guān)閉DataReaderreader.Close();〃關(guān)閉連接conn.Close();〃在GridView中綁定顯示內(nèi)存表DataTable的數(shù)據(jù)dg.DataSource=table;〃實現(xiàn)綁定dg.DataBind();}DataAdapter對象:由于DataSet對象本身不具備和數(shù)據(jù)庫溝通的能力,要修改數(shù)據(jù)并更新回數(shù)據(jù)源,需要DataAdapter對象。DataAdapter對象提供的是對數(shù)據(jù)集的填充和更新的回傳任務(wù),對于DataSet來說,DataAdapter對象有點像一個搬運工:它把數(shù)據(jù)從數(shù)據(jù)庫“搬運”到DataSet中,DataSet中的數(shù)據(jù)有個改動的時候,又可以把這些改動“反映”給數(shù)據(jù)庫。而DataAdapter對象做這件事情,靠的是它所包含的4個Command對象:l.SelectCommand:用于在數(shù)據(jù)源中選擇記錄的SQL命令2.InsertCommand:用來在數(shù)據(jù)源中插入新記錄的SQL命令3.UpdateCommand:用于更新數(shù)據(jù)源中的記錄的SQL命令4.DeleteComand:用來從數(shù)據(jù)集刪除記錄的SQL命令.創(chuàng)建DataAdapter對象一般用以下方式:SqlDataAdapterda=newSqlDataAdapter(selectSQL,Connection);其中,selectSQL為返回數(shù)據(jù)集的Select語句,Connection用于制定所用的連接。這種方式等價于另一種常用的DataAdapter對象創(chuàng)建方式:SqlDataAdapterda=newSqlDataAdapter();//創(chuàng)建DataAdapter對象SqlCommandcmd=newSqlCommand(selectSQL,conn);//創(chuàng)建Command對象da.SelectCommand=cmd;〃給DataAdapter的SelectCommand賦值實例演示如下:protectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=2012-20130315AP;uid=sa;pwd=xushouwei;database=student";〃建立Connection連接SqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建SqlDataAdapter對象SqlDataAdapterda=newSqlDataAdapter("selectstuId,stuName,Emailfromstudents",conn);〃創(chuàng)建DataSet對象DataSetds=newDataSet();〃使用SqlDataAdapter的Fill方法填充DataSetda.Fill(ds,"students");〃實現(xiàn)數(shù)據(jù)綁定oldGV.DataSource=ds;oldGV.DataBind();〃插入心的一行DataRowdr1=ds.Tables["students"].NewRow();drl["stuName"]="suxuan";dr1["Email"]="123456@163.com";ds.Tables["students"].Rows.Add(dr1);〃更新第二行DataRowdr2=ds.Tables["students"].Rows[1];dr2["stuName"]="hufeng";〃刪除第一行ds.Tables["students"].Rows[O].Delete();〃利用SqlCommandBuilder對象自動構(gòu)建SqlCommandBuildercb=newSqlCommandBuilder(da);da.Update(ds,"students");〃實現(xiàn)數(shù)據(jù)綁定newGV.DataSource=ds;newGV.DataBind();}利用SqlCommandBuilder對象生成的幾個Command的SQL命令實例演示:protectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=2012-20130315AP;uid=sa;pwd=xushouwei;database=student";〃建立Connection連接SqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建SqlDataAdapter對象SqlDataAdapterda=newSqlDataAdapter("selectstuId,stuName,QQ,Emailfromstudents",conn);〃利用SqlCommandBuilder對象自動構(gòu)建SqlCommandBuildercb=newSqlCommandBuilder(da);Response.Write("DeleteCommand的SQL:vbr>");Response.Write(cb.GetDeleteCommand().CommandText);Response.Write("vbr>UpdateCommand的SQL:<br>");Response.Write(cb.GetUpdateCommand().CommandText);Response.Write("vbr>InsertCommand的SQL:<br>");Response.Write(cb.GetInsertCommand().CommandText);}DataView對象:DataView對象可以自定義數(shù)據(jù)外觀,它是一種用來幫助用戶設(shè)置DataTable中的數(shù)據(jù)要如何顯示出來的對象,它本身不包含DataTable對象中的數(shù)據(jù)。通過DataView對象可以來過濾、排序、查找對應(yīng)DataTable中的數(shù)據(jù)。對DataView對象所執(zhí)行的任何操作都會影響原來的DataTable對象中的數(shù)據(jù)。DataTable對象提供一個DefaultView屬性,DefaultView屬性本身就是DataView對象,可以設(shè)置DefaultView的屬性來指定DataTable對象的顯示格式。如果DefaultView這個DataView對象無法滿足需求,還可以簡歷多個DataView對象來制定數(shù)據(jù)的顯示格式。語法聲明如下:DataViewdataview=newDataView(數(shù)據(jù)表);排序:DataView.Sort-字段ASC(升序)IDESC(降序)”;篩選:DataView.RowFilter—過濾條件";DataView對象實例演示如下:protectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=2012-20130315AP;uid=sa;pwd=xushouwei;database=student";〃建立Connection連接SqlConnectionconn=newSqlConnection(connStr);〃創(chuàng)建SqlDataAdapter對象SqlDataAdapterda=newSqlDataAdapter("select*fromstudents",conn);〃創(chuàng)建DataSet對象DataSetds=newDataSet();〃使用SqlDataAdapter的Fill方法填充DataSetda.Fill(ds,"students");〃創(chuàng)建DataView對象DataViewdv=newDataView(ds.Tables["students"]);〃篩選dv.RowFilter="stuId<5";府F序(降序)dv.Sort="QQDESC";Response.Write("滿足條件的記錄有:"+dv.Count+"條!”);〃實現(xiàn)數(shù)據(jù)綁定dg.DataSource=dv;dg.DataBind();}使用存儲過程(StoredProcedure):是有一些列SQL語句和控制語句組成的數(shù)據(jù)處理過程,它存放在數(shù)據(jù)庫中,在服務(wù)器段運行。1)執(zhí)行不帶參數(shù)的存儲過程:ADO.NET中執(zhí)行存儲過程,與執(zhí)行一般的SQL命令相似,不同之處有亮點:創(chuàng)建Command時候,命令語句CommandText為存儲過程名CommandType屬性設(shè)置為CommandType.StoredProcedure表示要執(zhí)行存儲過程。實例演示如下:首先在查詢分析其中運行如下的SQL語句,創(chuàng)建存儲過程P_1,P_1的功能是返回students表中的前三條記錄。:usestudentgocreateprocedurep_1asselecttop3stuId,stuName,EmailfromstudentsprotectedvoidPage_Load(objectsender,EventArgse){〃創(chuàng)建連接字符串stringconnStr="server=2012-20130315AP;uid=sa;pwd=xushouwei;database=student";〃建立Connection連接SqlConnectionconn=newSqlConnection(connStr);〃打開連接conn.Open();〃創(chuàng)建SqlDataAdapter對象SqlDataAdapterda=newSqlDataAdapter();〃倉U建commandSqlCommandcmd=newSqlCommand("p_1",conn);cmd.CommandType=CommandType.StoredProcedure;da.SelectCommand=cmd;〃創(chuàng)建DataSet對象DataSetds=newDataSet();〃使用SqlDataAdapter的Fill方法填充DataSetda.Fill(ds,"students");〃實現(xiàn)數(shù)據(jù)綁定dg.DataSource=ds;dg.DataBind();}2)執(zhí)行帶參數(shù)的存儲過程:實例演示如下:首先在查詢分析其中運行如下的SQL語句,創(chuàng)建存儲過程P_2。:usestudentcreateprocedurep_2@stuIdint,--學(xué)生的編號@stuNamevarc

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論