Enterprise Library 4.1學(xué)習(xí)筆記2----數(shù)據(jù)訪問程序塊Data Access Application Block 其實(shí)個(gè)人感覺相當(dāng)于另一個(gè)版本的dbHelper 廢話不多說,先看下如何使用: 1.引用Microsoft.Practices.EnterpriseLibrary.Data.dll(EL安裝目錄下的bin中就有) 2.配置web.config <configSections> 這一節(jié)是系統(tǒng)自動(dòng)加上去的,原來后面還有一截PublicKeyToken=....,不過在使用中發(fā)現(xiàn)系統(tǒng)總是報(bào)錯(cuò)無法加載EL程序集之類,所以到園子里搜索了下,參考前人的解決辦法去掉了這一段(可能是發(fā)行時(shí)版本不一致造成的) 此外還要添加連接字符串 <connectionStrings> 這跟常規(guī)的web開發(fā)幾乎沒什么不同,要說明的是<dataConfiguration defaultDatabase="Conn"/>這一節(jié)標(biāo)明了默認(rèn)情況下使用哪個(gè)連接字符串 3.下面可以正式使用了,示例代碼: using System;
using System.Data; using System.Data.Common; using Microsoft.Practices.EnterpriseLibrary.Data; namespace test { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Database db = DatabaseFactory.CreateDatabase("Conn"); //查詢數(shù)據(jù) //this.Repeater1.DataSource = db.ExecuteReader(CommandType.Text, "Select * from GoGo365"); //調(diào)用存儲(chǔ)過程(直接傳參數(shù)的簡(jiǎn)單調(diào)用) //this.Repeater1.DataSource = db.ExecuteReader("up_test", "2"); //切換數(shù)據(jù)庫 db = DatabaseFactory.CreateDatabase("Conn2"); //帶輸出和返回參數(shù)的存儲(chǔ)過程調(diào)用 DbCommand cmd = db.GetStoredProcCommand("up_Page2005"); db.AddInParameter(cmd, "TableName", DbType.String, "T_User"); db.AddInParameter(cmd, "Fields", DbType.String, "F_NickName"); db.AddInParameter(cmd, "OrderField", DbType.String, "F_Id"); db.AddInParameter(cmd, "sqlWhere", DbType.String, "F_Status=1"); db.AddInParameter(cmd, "PageSize", DbType.Int16, 50); db.AddInParameter(cmd, "PageIndex", DbType.Int16, 2); db.AddOutParameter(cmd, "TotalPage", DbType.Int16, 4); db.AddParameter(cmd, "RecordCount", DbType.Int16, ParameterDirection.ReturnValue, "", DataRowVersion.Default, 0); this.Repeater1.DataSource = db.ExecuteReader(cmd); this.Repeater1.DataBind(); Response.Write("輸出參數(shù)值:" + db.GetParameterValue(cmd, "TotalPage").ToString()); Response.Write("<br />返回參數(shù)值:" + db.GetParameterValue(cmd, "RecordCount").ToString()); //使用事務(wù) db = DatabaseFactory.CreateDatabase("Conn"); using (IDbConnection conn = db.CreateConnection()) { conn.Open(); IDbTransaction _trans = conn.BeginTransaction(); try { DbCommand _cmd = db.GetSqlStringCommand("Insert Into GoGo365(F_NickName) values(@NickName)"); db.AddInParameter(_cmd, "NickName", DbType.String, "AA"); db.ExecuteNonQuery(_cmd, _trans as DbTransaction); db.ExecuteNonQuery(_cmd, _trans as DbTransaction);//F_NickName字段上建有唯一索引,故第二次插入同樣記錄時(shí)會(huì)報(bào)錯(cuò) _trans.Commit(); } catch { try { _trans.Rollback();//事務(wù)提交失敗時(shí),則回滾(是否回滾成功,可查看表中有無AA的記錄即可) } catch { } } finally { conn.Close(); } } } } } 基本上涉及數(shù)據(jù)庫操作的東東都已經(jīng)在里面了,更多功能大家自己去體驗(yàn)吧
|
|