使用microsoft EnterpriseLibrary連接不同數據庫簡單應用

 在做asp.net開發都會遇到連接數據源的問題,只要有數據交換就會存在這個問題。如果自己獨立寫這層操作,不一定能保證代碼的各個方面的問題,如果有一個現成的類庫,那效果就不同了。尤其對於那些初學者來說,這是第一要跨越的坎。這個問題現在已經有很好的解決方法,還可以算得上是microsoft官方是解決方案,那就是Enterprise Library,從名稱就可以看出大概的應用範圍。
接下來就簡單的介紹一下這個類庫的一部分中的數據應用使用方法:
首先需要準備的有:Enterprise Library、Visual Studio、Sql Server DataBase、Oracle DataBase、Access DataBase、MySQL、Mysql-Connector
提供下載鏈接:
Enterprise Library:http://msdn.microsoft.com/zh-cn/library/cc467894(en-us).aspx
mysql-connector:http://dev.mysql.com/downloads/connector/net/5.2.html
MySQL:http://dev.mysql.com/downloads/mysql/

其次就是把這些程序都給安裝好,其中重點就是Enterprise Library,其他的數據庫安裝就不累贅了。

Enterprise Library對很多人來說應該還是比較的神祕的吧,國內應該採用這個的單位、組織、個人應該不多,談到這個不得不提到petshop的多層設計框架,參考該設計框架的比較出名的公司就不乏動易這樣的知名公司。

Enterprise Library安裝文件提供了源碼、示例、文檔(English)、配置工具,在其安裝目錄裏可以找到,很好很強大,O(∩_∩)O哈哈~

不廢話了,現在就開始Enterprise Library體驗吧!
用Visual Studio建立解決方案,建立網站項目,並引用Microsoft.Practices.EnterpriseLibrary.Data

vs會自動把相關文件也給一起引用過來並複製到bin目錄下:

接下來我們就需要配置web.config文件了,在vs中打開該文件,沒有就新建一個,用Enterprise Library自帶的配置工具打開:

在web.config文件中加入:
<configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>

  <dataConfiguration defaultDatabase="Connection String MySql" />
<add name="Connection String" connectionString="server=(local);database=name;uid=user;pwd=password"
    providerName="System.Data.SqlClient" />
<add name="Connection String Oracle" connectionString="server=(local);database=name;uid=user;pwd=password"
    providerName="System.Data.OracleClient" />
  <add name="Connection String Access" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|DataBase.mdb"
    providerName="System.Data.OleDb" />
  <add name="Connection String MySql" connectionString="server=localhost;user id=user;password=password;database=mysql"
    providerName="MySql.Data.MySqlClient" />
其中這裏就是默認連接數據庫的信息:
  <dataConfiguration defaultDatabase="Connection String MySql" />
到這裏準備工作到位,接着就測試與數據庫的連接是否正常,新建一個webform,引用中添加:
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
接着建立一個gridview,在後臺代碼中添加如下代碼:
Database db = DatabaseFactory.CreateDatabase();
DbCommand command = db.GetSqlStringCommand("SELECT * FROM mysql.`user` u WHERE host='localhost';");

IDataReader dr = db.ExecuteReader(command);

GridView1.DataSource = dr;
GridView1.DataBind();
運行該webform,等一下就可以從數據庫中提出了該表是全部信息。本示例中的連接的數據庫爲MySQL,其他的類似。
數據應用部分可參考如下中文手冊(只有3.1版):
http://wiki.entlib.net.cn/(S(miapvyqfwbq5ki55xpk4llvn))/EnterpriseLibraryHelp31.ashx
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章