ADO.NET基礎(chǔ)知識(shí)匯總
雖然我們都知道ADO.NET是對(duì)數(shù)據(jù)庫(kù)的操作,但是要真的說(shuō)出ADO.NET的具體含義還不是很容易。
ADO.NET是ActiveX Data Objects的縮寫,它是一個(gè)COM組件庫(kù),用于在microsoft技術(shù)中訪問(wèn)數(shù)據(jù)。之所以叫ADO.NET,應(yīng)該是微軟自己打的廣告,希望在NET編程環(huán)境中優(yōu)先使用這種數(shù)據(jù)訪問(wèn)接口。上面這段話基本來(lái)自百度百科。簡(jiǎn)單來(lái)說(shuō),ADO.NET就是一種數(shù)據(jù)訪問(wèn)接口,可以讓我們?cè)诔绦蛑姓{(diào)用相應(yīng)的類庫(kù)對(duì)數(shù)據(jù)庫(kù)(通常為SQL Server,也可以是access 等其他數(shù)據(jù)庫(kù))進(jìn)行增刪改查等操作。
ADO.NET的幾大組成部分
ADO.NET由五大類庫(kù)組成,分別是:
Connection(用于建立與 數(shù)據(jù)庫(kù)的連接)
Command(用于執(zhí)行SQL語(yǔ)句)
DataReader(用于讀取數(shù)據(jù))
DataAdapter(用于填充把數(shù)據(jù)填充到DataSet)
DataSet(數(shù)據(jù)集,用于程序中)
通常,從程序中訪問(wèn)數(shù)據(jù)庫(kù)的方法是:
創(chuàng)建一個(gè)到數(shù)據(jù)庫(kù)的連接
打開數(shù)據(jù)庫(kù)連接
創(chuàng)建ADO記錄集
從記錄集中提取需要的數(shù)據(jù)
關(guān)閉記錄集
關(guān)閉連接
下面就分別根據(jù)這一個(gè)過(guò)程結(jié)合ADO.NET的五大類庫(kù)進(jìn)行解釋。
要想使用ADO.NET需要在程序中引用System.Data.SqlClient。其中包含了對(duì)Sql Server進(jìn)行操作的數(shù)據(jù)訪問(wèn)類:
SqlConnection:連接數(shù)據(jù)庫(kù)
SqlCommand:數(shù)據(jù)庫(kù)命名對(duì)象
SqlCommandBuilder:生成SQL命令
SqlDataReader:數(shù)據(jù)讀取器
SqlDataAdapter:數(shù)據(jù)適配器,用于填充DataSet
SqlParameter:為存儲(chǔ)過(guò)程定義參數(shù)
SqlTransaction:數(shù)據(jù)庫(kù)事務(wù)
建立連接
首先,要想訪問(wèn)數(shù)據(jù)庫(kù),我們需要一個(gè)媒介把程序與數(shù)據(jù)庫(kù)連接起來(lái)。這就是連接字符串,它的基本語(yǔ)法為:Data Source(數(shù)據(jù)源) + Initial Catalog(數(shù)據(jù)庫(kù)名稱) + User ID(用戶名) + Password(密碼)。
String connectString = "Data Source = myServerAddress;Initial Catalog = myDataBase;User Id = myUserName; Password = myPassword;";
或者
String connectString = "Server =myServerAddress;Database = myDataBase; User Id = myUsername; Password = myPassword;";
注意:對(duì)于Sql Server來(lái)說(shuō),它支持兩種身份驗(yàn)證方法,一種是windows身份驗(yàn)證,另一種是Sql Server身份驗(yàn)證。如果要用windows身份驗(yàn)證,就需要在連接字符串中包括Integrated Security屬性。該屬性默認(rèn)為False。需要設(shè)置為True后才能使用windows身份驗(yàn)證。
除了這幾個(gè)必須的字段,連接字符串中還有許多可選的屬性,在這里我就不一一列舉,列出一些相關(guān)資料供感興趣的朋友自行查閱,一個(gè)連接字符串可以包含哪些屬性(http://www.dbjr.com.cn/article/67742.htm)。
接著,有了連接字符串就可以創(chuàng)建連接對(duì)象了。
SqlConnection connection = new SqlConnection(connecString);
或者可以使用專門的連接字符串生成器:
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder()
{
DataSource=”“,
InitialCatalog=”“,
UserID=”“,
Password=””
};
SqlConnection connection = new SqlConnection(connectionStringBuilder.ToString());
然后使用連接對(duì)象可以打開或關(guān)閉連接。
connection.Open();
connection.Close();
執(zhí)行命令
打開連接之后就可以操作數(shù)據(jù)庫(kù)了,在這里需要用到SqlCommand命令對(duì)象。
它具有四個(gè)主要屬性,這些屬性會(huì)在初始化的時(shí)候賦默認(rèn)值:
CommandText:空字符串(”“)
CommandTimeout:30
CommandType:CommandType.Text
Connection:Null
創(chuàng)建命令對(duì)象:
SqlCommand command = connection.CreateCommand();
或
SqlCommand command = new SqlCommand();
SqlCommand包含了幾個(gè)重要的屬性:
CommandText:用于獲取或設(shè)置藥對(duì)數(shù)據(jù)源之行的SQL語(yǔ)句、表明或存儲(chǔ)過(guò)程。
CommandType:設(shè)置你執(zhí)行的SQL語(yǔ)句類型,有三個(gè)枚舉,分別是Text(SQL文本命令),StoredProcedure(存儲(chǔ)過(guò)程),TableDirect(表名)。
Parameters:設(shè)置你的T-SQL中需要用到的參數(shù)。
幾個(gè)重要的方法:
ExecuteNonQuery:返回被SQL語(yǔ)句執(zhí)行影響的行數(shù)(int),主要執(zhí)行增刪改操作。
ExecuteReader:執(zhí)行SQL或存儲(chǔ)過(guò)程,返回的是SqlDataReader類型,主要用來(lái)查詢。
ExecuteScalar:返回執(zhí)行結(jié)果集中的第一行第一列,如果沒有數(shù)據(jù),則返回NULL。
CreateParameter:創(chuàng)建SqlParameter實(shí)例。
舉例說(shuō)明:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data;//必須 using System.Data.SqlClient;//必須 namespace Command { class Program { static void Main(string[] args) { SqlConnectionStringBuilder conStr = new SqlConnectionStringBuilder(); conSt.DataSource=@".\SQLEXPRESS"; conStr.IntegratedSecurity=true; conStr.InitialCatalog="db_Test"; StringBuilder strSQL = new StringBuilder(); for(int i=0;i<=100;i++) { strSQL.Append("insert into tb_Test"); strSQL.Append("values('"); string name = "test"+i.ToString(); strSQL.Append(name); } using(SqlConnection con = new SqlConnection(conStr.ConnectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(strSQL.ToString(),con); int impactedNumber = cmd.ExecuteNonQuery();//返回受影響的行數(shù) object firstData = cmd.ExecuteScalar();//返回執(zhí)行結(jié)果中的第一行第一列,此方法可用于獲取插入數(shù)據(jù)的ID,(int lineNumber =(int)cmd.ExecuteScalar();) } } } }
SQL參數(shù)
若想在程序中傳遞參數(shù)給數(shù)據(jù)庫(kù),可以使用SqlParameter。該類有幾個(gè)重要的屬性:
ParameterName:設(shè)置參數(shù)名
Value:給參數(shù)設(shè)置值
Size:設(shè)置參數(shù)字節(jié)最大長(zhǎng)度
SqlDbType:參數(shù)在SQL中的類別
和幾個(gè)重要的方法:
AddWithVlue
Add
AddRange
舉例說(shuō)明:
SqlConnection connection =new SqlConnection("")) { SqlCommand cmd = connection.CreateCommand(); cmd.CommandText=""; cmd.Parameters.Add("@name",SqlDbType.NVarChar).Value = "deng";//方法一 cmd.Parameters.AddWithValue(@"name","deng");//方法二 SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@name",SqlDbType.NvarChar,100){Value="deng"}, }; cmd.Parameters.AddRange(parameters);//可以放一個(gè)參數(shù)數(shù)組,包含多條參數(shù),在此只舉一個(gè)例子 }
可以通過(guò)cmd.Parameters[i].Value設(shè)置和讀取數(shù)值。
數(shù)據(jù)讀取
利用查詢語(yǔ)句得到的數(shù)據(jù)信息需要通過(guò)數(shù)據(jù)讀取器進(jìn)行操作。
舉例:
SqlConnetion con = new SqlConnection("") { con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText=""; SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) { While(dr.Read()) { string str = dr.GetSqlString(0).ToString(); } } }
介紹幾個(gè)常用的方法:
GetOrdinal:可以獲取指定列名的序列號(hào),int name = dr.GetOrdinal(“name”);
GetName:與上面的方法對(duì)應(yīng),可以通過(guò)列號(hào)返回列名字。
IsDBNull:判斷當(dāng)前讀取的數(shù)據(jù)是否為Null。
NextResult:當(dāng)查詢?yōu)榕幚聿樵儠r(shí),使用這個(gè)方法去獲取下一個(gè)結(jié)果集,返回值為Bool,如果存在多個(gè)結(jié)果集,則為true;否則為false。
Read:讀取數(shù)據(jù)。
常用屬性有:
HasRow:判斷是否有數(shù)據(jù)。
FieldCount:獲取讀取的列數(shù)。
IsClosed:判斷讀取的數(shù)據(jù)流是否關(guān)閉。
SqlDataReader是連接相關(guān)的,也就是說(shuō)與數(shù)據(jù)庫(kù)的連接一斷開就無(wú)法讀取數(shù)據(jù)庫(kù)中的數(shù)據(jù),說(shuō)明查詢結(jié)果并不是放在程序中,而是放在數(shù)據(jù)庫(kù)的服務(wù)中。
事務(wù)
需要用到SqlTransaction類,需要在指定位置命名存儲(chǔ)點(diǎn),該存儲(chǔ)點(diǎn)之后的操作都將會(huì)回滾。
例子:
SqlConnection con = new SqlConnection(strCon); con.Open(); SqlTransaction transaction = con.BeginTransaction(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "" cmd.Transaction = transaction; transaction.Save("transaction point"); transaction.Rollback("transaction point");
數(shù)據(jù)適配器
SqlDataAdapter類有四個(gè)重載構(gòu)造函數(shù):
無(wú)參
SqlDataAdapter(SqlCommand)
SqlDataAdapter(String,SqlConnection)
SqlDataAdapter(String, ConnectionString)
填充數(shù)據(jù)例子:
DataSet dataSet = new DataSet(); SqlConnection con = new SqlConnection(""); con.Open(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText="select xxx from tb_xxx"; SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); dataAdapter.Fill(dataSet);
填充后的數(shù)據(jù)可以使用SqlCommandBuilder進(jìn)行增刪改查。
例子:
SqlConnection con = new SqlConnection(ConnectionString(); con.Open(); SqlDataAdapter da = new SqlDataAdapter("select xxx from tb_xx"); DataSet ds =new DataSet(); da.Fill(ds); SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da); DataRow row = ds.Tables[0].NewRow(); row[0]="a"; row[1]="b"; ds.Tables[0].Rows.Add(row); da.Update(ds);
SqlCommandBuilder 可以把DataSet增加的數(shù)據(jù)轉(zhuǎn)化為SQL語(yǔ)句用來(lái)更新數(shù)據(jù)庫(kù)。然后調(diào)用Update方法。
總結(jié)
因?yàn)楝F(xiàn)在使用的框架或著庫(kù)都已經(jīng)封裝了ADO.NET,可能在日常工作中很少會(huì)再?gòu)念^開始編寫ADO.NET來(lái)連接數(shù)據(jù)庫(kù),但是在.net面試中還是非常常見的,希望可以借此加深一下印象。另外,本人目前持有的是銀蕨簽證,可以在新西蘭求職9個(gè)月,期間如果找到相關(guān)專業(yè)工作,可直接轉(zhuǎn)2年的工作簽證,非常方便移民,該簽證每年全球發(fā)放300個(gè),雖然還沒有working holiday簽證為大家所熟知,但是每年的爭(zhēng)搶還是很激烈的。需要了解相關(guān)事宜的可以給我留言。本人的第一篇博客,屬于整理資料,并非完全原創(chuàng),如有哪方面不正確,還希望大神可以多多指正。
相關(guān)文章
asp.net下URL網(wǎng)址重寫成.html格式、RSS、OPML的知識(shí)總結(jié)
asp.net下URL網(wǎng)址重寫成.html格式、RSS、OPML的知識(shí)總結(jié)...2007-09-09asp.net編程獲取項(xiàng)目根目錄實(shí)現(xiàn)方法集合
這篇文章主要介紹了asp.net編程獲取項(xiàng)目根目錄實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析總結(jié)了asp.net針對(duì)項(xiàng)目目錄的操作技巧與注意事項(xiàng),需要的朋友可以參考下2015-11-11Redis數(shù)據(jù)庫(kù)基礎(chǔ)與ASP.NET?Core緩存實(shí)現(xiàn)
這篇文章介紹了Redis數(shù)據(jù)庫(kù)基礎(chǔ)與ASP.NET?Core緩存實(shí)現(xiàn)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02ASP.NET MVC分頁(yè)的實(shí)現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了ASP.NET MVC分頁(yè)的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03asp.net下將頁(yè)面內(nèi)容導(dǎo)入到word模板中的方法
asp.net下將頁(yè)面內(nèi)容導(dǎo)入到word模板中的方法,需要的朋友可以參考下。2010-10-10.Net整合Json實(shí)現(xiàn)REST服務(wù)客戶端的方法詳解
這篇文章主要給大家介紹了關(guān)于.Net整合Json實(shí)現(xiàn)REST服務(wù)客戶端的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01