原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Access Application Block

企业库数据库访问模块通过抽象工厂模式,允许用户通过简单的配置选择不同的数据库作为程序的数据源,大大解决了切换数据库时带来的麻烦.因为我本机只安装了SQL Server 2005,所以在此只做SQL的演示,需要深究的朋友可以访问以下网站:

http://msdn.microsoft.com/en-us/library/ff664408%28v=PandP.50%29.aspx

企业库数据库访问模块的几大功能:

1.        最简单的功能,通过ExecuteNonQuery.方法执行SQL语句.

2.        执行ExecuteDataSet,返回DataSet类型的数据集.

3.        执行ExecuteScalar,获取返回的第一行第一列的信息.

4.        执行存储过程.

5.        通过代码实现事务.

6.        通过DataSet更新数据库.

7.        返回值XML化.

8.       将返回的数据对象化.

9.       异步访问数据库.

以上的功能我会在下面一一介绍,测试程序我已打包,大家可以点击这里下载.

下面介绍如何使用Microsoft Enterprise Library 5.0中的数据库访问模块.

1.   首先创建一个测试数据库,创建数据库的SQL文件我打包在压缩包里了,大家可以点击上面的下载链接下载.执行完SQL文件后,可以看到我们创建好的TestDB数据库:

2.   下载安装好MicrosoftEnterprise Library 5.0,然后在运行EntLibConfig.exe,选择Blocks菜单 ,单击 AddDatabase Settings .

 

3.    配置好文件之后保存为App.config文件,并添加到创建好的应用程序中.并添加相应的引用,在此我不再多讲,大家下载我打包好的程序运行即可看到

4.      下面来介绍我在应用程序中实现的各个功能:

(1)     通过ExecuteNonQuery.方法执行SQL语句:

///<summary>/// 执行ExecuteNonQuery///</summary>privatevoid ExecuteNonQuery_Click(object sender, EventArgs e){    db.ExecuteNonQuery(CommandType.Text, "INSERT INTO [College] ([CollegeID],[Name]) values (6,'体育学院')");}

(2)    执行ExecuteDataSet,返回DataSet类型的数据集.

///<summary>/// 执行ExecuteDataSet,返回College列表///</summary>///<returns></returns>privatevoid ExecuteDataSet_Click(object sender, EventArgs e){    string sql ="select * from College";    DbCommand dw = db.GetSqlStringCommand(sql);    dataGridView1.DataSource = db.ExecuteDataSet(dw).Tables[];}

(3)    执行ExecuteScalar,返回第一行第一列的值.

///<summary>/// 执行ExecuteScalar,返回第一行第一列的值///</summary>///<returns></returns>privatevoid ExecuteScalar_Click(object sender, EventArgs e){    Database db = DatabaseFactory.CreateDatabase("ConnectionString");    string sql ="select [Name] from College where [CollegeID] = 1";    DbCommand dc = db.GetSqlStringCommand(sql);    string str ="获取的学院名称为:"+ (string)db.ExecuteScalar(dc);    MessageBox.Show(str);    sql ="select [CollegeID] from College where [CollegeID] = 1";    dc = db.GetSqlStringCommand(sql);    str ="获取的学院ID为:"+ (int)db.ExecuteScalar(dc);    MessageBox.Show(str);}

(4)    执行存储过程.

///<summary>/// 执行存储过程///</summary>privatevoid StoredProcCommand_Click(object sender, EventArgs e){    DbCommand dc = db.GetStoredProcCommand("usp_College_LoadByID");    db.AddInParameter(dc, "@CollegeID", System.Data.DbType.Int32, );    dataGridView1.DataSource = db.ExecuteDataSet(dc).Tables[];}

(5)    通过代码实现事务.

///<summary>/// 事务///</summary>privatevoid Transaction_Click(object sender, EventArgs e){    DbCommand dc1 = db.GetStoredProcCommand("usp_College_Insert");    db.AddInParameter(dc1, "@CollegeID", DbType.Int32, );    db.AddInParameter(dc1, "@Name", DbType.String, "文旅学院");    DbCommand dc2 = db.GetStoredProcCommand("usp_College_Insert");    db.AddInParameter(dc2, "@CollegeID", DbType.Int32, );    db.AddInParameter(dc2, "@Name", DbType.String, "化工学院");    using (DbConnection conn = db.CreateConnection())    {        conn.Open();        DbTransaction trans = conn.BeginTransaction();        try        {            //添加一个ID为7的学院            db.ExecuteNonQuery(dc1, trans);            //添加一个ID为7的学院,主键重复,事务将回滚            db.ExecuteNonQuery(dc2, trans);            //提交事务.            trans.Commit();        }        catch        {            //回滚            trans.Rollback();        }        conn.Close();    }    //查看数据库,数据未被添加,说明事务已回滚    ExecuteDataSet_Click(null, null);}

(6)    通过DataSet更新数据库.

///<summary>/// 通过DataSet更新数据库///</summary>privatevoid DataSetUpdate_Click(object sender, EventArgs e){    DataSet productsDataSet =new DataSet();    string sql ="Select * From College";    DbCommand cmd = db.GetSqlStringCommand(sql);    string CollegeTableName ="College";    //恢复原始数据    db.LoadDataSet(cmd, productsDataSet, CollegeTableName);    //获取数据表格    DataTable dTable = productsDataSet.Tables[CollegeTableName];    //添加一个新信息入DataSet中    DataRow addedRow = dTable.Rows.Add(newobject[] { , "外国语学院" });    //修改一个原有数据    dTable.Rows[]["Name"] ="国教院";    //提供插入,更新,删除存储过程    DbCommand insertCommand = db.GetStoredProcCommand("usp_College_Insert");    db.AddInParameter(insertCommand, "@CollegeID", DbType.Int32, "CollegeID", DataRowVersion.Current);    db.AddInParameter(insertCommand, "@Name", DbType.String, "Name", DataRowVersion.Current);    DbCommand deleteCommand = db.GetStoredProcCommand("usp_College_Delete");    db.AddInParameter(deleteCommand, "@CollegeID", DbType.Int32, "CollegeID", DataRowVersion.Current);    DbCommand updateCommand = db.GetStoredProcCommand("usp_College_Update");    db.AddInParameter(updateCommand, "@CollegeID", DbType.Int32, "CollegeID", DataRowVersion.Current);    db.AddInParameter(updateCommand, "@Name", DbType.String, "Name", DataRowVersion.Current);    //通过DataSet更新数据库int rowsAffected = db.UpdateDataSet(productsDataSet, CollegeTableName, insertCommand, updateCommand, deleteCommand,                        Microsoft.Practices.EnterpriseLibrary.Data.UpdateBehavior.Standard);    MessageBox.Show("影响的行数:"+ rowsAffected);}

(7)    返回值XML化.

///<summary>/// 返回值XML化///</summary>privatevoid ReturnXML_Click(object sender, EventArgs e){    //使用"FOR XML AUTO"参数使得SQL返回XML格式的信息    SqlDatabase sqldb = (SqlDatabase)DatabaseFactory.CreateDatabase("ConnectionString");    DbCommand cmd = sqldb.GetSqlStringCommand("SELECT * FROM College FOR XML AUTO");    IEnumerable<string> productList;    using (var reader = sqldb.ExecuteXmlReader(cmd))    {        if (reader.IsStartElement())        {            var root = (XElement)XNode.ReadFrom(reader);            productList = root.Elements("CollegeID")                              .Attributes("Name")                              .Select(a => a.Value).ToArray();            MessageBox.Show(((XElement)root).ToString());        }    }}

(8)    将返回的数据对象化.

///<summary>/// DataAsObject///</summary>privatevoid DataAsObject_Click(object sender, EventArgs e){    //将返回的数据对象化    var results = db.ExecuteSprocAccessor<College>("usp_College_LoadAll");    MessageBox.Show(results.ElementAt().ToString());}

(9)    异步访问数据库.

///<summary>/// 异步访问数据库///</summary>privatevoid Async_Click(object sender, EventArgs e){    //创建新的数据库连接,属性必须添加:Asynchronous Processing=true    String connectionString =@"server=(local); database=TestDB; Integrated Security=true; Asynchronous Processing=true";    Database Sqldb =new SqlDatabase(connectionString);    DbCommand cmd = Sqldb.GetStoredProcCommand("usp_College_LoadbyID");    Sqldb.AddInParameter(cmd, "@CollegeID", DbType.Int32, );    try    {        IAsyncResult result = Sqldb.BeginExecuteReader(cmd, MyEndExecuteCallback, Sqldb);    }    catch (Exception ex)    {        MessageBox.Show(ex.ToString());    }}//当获取完毕执行该函数privatevoid MyEndExecuteCallback(IAsyncResult result){    try    {        Database Sqldb = (Database)result.AsyncState;        IDataReader reader = db.EndExecuteReader(result);        College c =new College((int)reader[], (string)reader[]);        MessageBox.Show(c.ToString());    }    catch(Exception ex)    {        MessageBox.Show(ex.ToString());    }}

黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Access Application Block的更多相关文章

  1. 黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block 使用企业库异常处理应用程序模块的 ...

  2. 黄聪:Microsoft Enterprise Library 5.0 系列教程(九) Policy Injection Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(九) Policy Injection Application Block 代理对象(Proxy Object) ...

  3. 黄聪:Microsoft Enterprise Library 5.0 系列教程(六) Security Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(六) Security Application Block 开发人员经常编写需要安全功能的应用程序.这些应用程序 ...

  4. 黄聪:Microsoft Enterprise Library 5.0 系列教程(四) Logging Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(四) Logging Application Block 企业库日志应用程序模块工作原理图:   从上图我们可以 ...

  5. 黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (高级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (高级) 企业库验证应用程序模块之配置文件模式: ...

  6. 黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (初级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (初级) 企业库提供了一个很强大的验证应用程序模 ...

  7. 黄聪:Microsoft Enterprise Library 5.0 系列教程(二) Cryptography Application Block (高级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(二) Cryptography Application Block (高级) 本章介绍的是企业库加密应用程序模块 ...

  8. 黄聪:Microsoft Enterprise Library 5.0 系列教程(二) Cryptography Application Block (初级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(二) Cryptography Application Block (初级) 企业库加密应用程序模块提供了2种方 ...

  9. 黄聪:Microsoft Enterprise Library 5.0 系列教程(一) Caching Application Block (高级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(一) Caching Application Block (高级) Caching Application Bl ...

随机推荐

  1. jfinal框架教程-学习笔记

    jfinal框架教程-学习笔记 JFinal  是基于 Java  语言的极速  WEB  + ORM  开发框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩展.Restfu ...

  2. Aerospike | Aerospike Chinese

    Aerospike | Aerospike Chinese 如果您的企业依赖于: 庞大的数据量(超过任何结构化数据库所能处理的数据量) 可预见(且快速)的性能 透明的扩展 始终正常运行 那么您只有一个 ...

  3. [Android开发Tips]Bean的定义

    Bean: public class Data extends BaseBean { public ArrayList<DataItem> data = new ArrayList< ...

  4. Codeforces Round #235 (Div. 2) D. Roman and Numbers (数位dp、状态压缩)

    D. Roman and Numbers time limit per test 4 seconds memory limit per test 512 megabytes input standar ...

  5. SilkTest高级进阶系列6-motif tag

    看SilkTest代码的时候不小心看到winclass.inc里面的一些类申明使用的是motif tag,例如: [-] winclass MessageBoxClass : DialogBox [ ...

  6. 小侃#pragma

    #pragma是一个编译器指令. ================================================================ #pragma comment(li ...

  7. ExtJS学习-------Ext正确Dom操作:Ext.get Ext.fly Ext.getDom

    详细实例: (1)创建JSP文件.引入CSS和js文件,加入三个Div <%@ page language="java" import="java.util.*&q ...

  8. python 入门学习---模块导入三种方式及中文凝视

    Python 有三种模块导入函数 1. 使用import 导入模块 import modname : 模块是指一个能够交互使用,或者从还有一Python 程序訪问的代码段.仅仅要导入了一个模块,就能够 ...

  9. 公布AppStore被拒绝的经历

    我们知道IOS发布的版本有很多原因是苹果拒绝发表,我总结了这里3手头上做的原因,他拒绝游,包括同事.朋友拒绝的理由,IOS app参考朋友. 1. 使用非公开API该计划将被拒绝 2. beta版.d ...

  10. linux它SQL声明简明教程---WHERE

    我们并不一定必须注意,每次格里面的信息是完全陷入了.在很多情况下,我们需要有选择性地捕捞数据.对于我们的样本.我们可以只抓住一个营业额超过 $1,000 轮廓. 做这个事情,我们就须要用到 WHERE ...