Enterprise Library2.0(1):Data Access Application Block学习
Data Access Application Block提供了通用的数据访问的功能,随着2.0版本的推出有了很大变化。
一.改进
在DAAB1.1里面我们知道Database方法返回或者创建一个DBCommandWrapper对象,而在DAAB2.0里面移除了DBCommandWrapper类,用ADO.NET2.0里面的DBCommand类代替实现类似的功能,这样使得DAAB跟我们的.NET类库的结合更加紧密,回忆一下我们在1.1里面用DBCommandWrapper来访问数据时的代码:
DBCommandWrapper dbCommand = db.GetStoredProcCommandWrapper("GetProductsByCategory");
dbCommand.AddInParameter("CategoryID", DbType.Int32, Category);
DataSet productDataSet = db.ExecuteDataSet(dbCommand);
而用了新的DBCommand类之后则变成了:
DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory");
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, Category);
DataSet productDataSet = db.ExecuteDataSet(dbCommand);
数据库连接字符串在我们基于数据库的开发永远是少不了的,但是在DAAB1.1下,它所使用的字符串跟我们在.NET类库中使用的连接字符串却是不能共享的,它们分别保存在不同的位置。而在2.0的Data Access Application Block使用了ADO.NET2.0里面<connectionStrings>配置区,这样带来的一个好处是连接字符串可以在Application Block和自定义的.NET类之间共享使用该配置区,如:
<add
name="DataAccessQuickStart"
providerName="System.Data.SqlClient"
connectionString="server=(local)\SQLEXPRESS;database=EntLibQuickStarts;Integrated Security=true" />
</connectionStrings>
在.NET2.0下,泛型编程已经成为了一个核心,而2.0版的DAAB中也新增了一个GenericDatabase对象。DAAB中虽然已经包含了SqlDatabase和OrcaleDatabase,但是如果我们需要使用其他的像DB2等数据库时,就需要用到GenericDatabase,它可以用于任何.NET类库中的数据提供者,包括OdbcProvider和OleDbProvider。
二.使用示例
DAAB2.0的配置非常简单,主要有以下几方面的配置:
配置连接字符串
配置默认数据库
添加相关的命名空间:
using System.Data;
使用Data Access Application Block进行数据的读取和操作,一般分为三步:
1.创建Database对象
2.提供命令参数,如果需要的话
3.执行命令
下面分别看一下DataAccessQuickStart中提供的一些例子:
执行静态的SQL语句
{
// 创建Database对象
Database db = DatabaseFactory.CreateDatabase();
// 使用SQL语句创建DbCommand对象
string sqlCommand = "Select CustomerID, Name, Address, City, Country, PostalCode " +
"From Customers";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
StringBuilder readerData = new StringBuilder();
// 调用ExecuteReader方法
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
// Get the value of the 'Name' column in the DataReader
readerData.Append(dataReader["Name"]);
readerData.Append(Environment.NewLine);
}
}
return readerData.ToString();
}
执行存储过程并传递参数,返回DataSet
{
// Create the Database object, using the default database service. The
// default database service is determined through configuration.
Database db = DatabaseFactory.CreateDatabase();
string sqlCommand = "GetProductsByCategory";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);
// Retrieve products from the specified category.
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, Category);
// DataSet that will hold the returned results
DataSet productsDataSet = null;
productsDataSet = db.ExecuteDataSet(dbCommand);
// Note: connection was closed by ExecuteDataSet method call
return productsDataSet;
}
利用DataSet更新数据
{
// Create the Database object, using the default database service. The
// default database service is determined through configuration.
Database db = DatabaseFactory.CreateDatabase();
DataSet productsDataSet = new DataSet();
string sqlCommand = "Select ProductID, ProductName, CategoryID, UnitPrice, LastUpdate " +
"From Products";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
string productsTable = "Products";
// Retrieve the initial data
db.LoadDataSet(dbCommand, productsDataSet, productsTable);
// Get the table that will be modified
DataTable table = productsDataSet.Tables[productsTable];
// Add a new product to existing DataSet
DataRow addedRow = table.Rows.Add(new object[] {DBNull.Value, "New product", 11, 25});
// Modify an existing product
table.Rows[0]["ProductName"] = "Modified product";
// Establish our Insert, Delete, and Update commands
DbCommand insertCommand = db.GetStoredProcCommand("AddProduct");
db.AddInParameter(insertCommand, "ProductName", DbType.String, "ProductName", DataRowVersion.Current);
db.AddInParameter(insertCommand, "CategoryID", DbType.Int32, "CategoryID", DataRowVersion.Current);
db.AddInParameter(insertCommand, "UnitPrice", DbType.Currency, "UnitPrice", DataRowVersion.Current);
DbCommand deleteCommand = db.GetStoredProcCommand("DeleteProduct");
db.AddInParameter(deleteCommand, "ProductID", DbType.Int32, "ProductID", DataRowVersion.Current);
DbCommand updateCommand = db.GetStoredProcCommand("UpdateProduct");
db.AddInParameter(updateCommand, "ProductID", DbType.Int32, "ProductID", DataRowVersion.Current);
db.AddInParameter(updateCommand, "ProductName", DbType.String, "ProductName", DataRowVersion.Current);
db.AddInParameter(updateCommand, "LastUpdate", DbType.DateTime, "LastUpdate", DataRowVersion.Current);
// Submit the DataSet, capturing the number of rows that were affected
int rowsAffected = db.UpdateDataSet(productsDataSet, "Products", insertCommand, updateCommand,
deleteCommand, UpdateBehavior.Standard);
return rowsAffected;
}
通过ID获取记录详细信息
{
// Create the Database object, using the default database service. The
// default database service is determined through configuration.
Database db = DatabaseFactory.CreateDatabase();
string sqlCommand = "GetProductDetails";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);
// Add paramters
// Input parameters can specify the input value
db.AddInParameter(dbCommand, "ProductID", DbType.Int32, productID);
// Output parameters specify the size of the return data
db.AddOutParameter(dbCommand, "ProductName", DbType.String, 50);
db.AddOutParameter(dbCommand, "UnitPrice", DbType.Currency, 8);
db.ExecuteNonQuery(dbCommand);
// Row of data is captured via output parameters
string results = string.Format(CultureInfo.CurrentCulture, "{0}, {1}, {2:C} ",
db.GetParameterValue(dbCommand, "ProductID"),
db.GetParameterValue(dbCommand, "ProductName"),
db.GetParameterValue(dbCommand, "UnitPrice"));
return results;
}
以XML格式返回数据
{
// Use a named database instance that refers to a SQL Server database.
SqlDatabase dbSQL = DatabaseFactory.CreateDatabase() as SqlDatabase;
// Use "FOR XML AUTO" to have SQL return XML data
string sqlCommand = "Select ProductID, ProductName, CategoryID, UnitPrice, LastUpdate " +
"From Products FOR XML AUTO";
DbCommand dbCommand = dbSQL.GetSqlStringCommand(sqlCommand);
XmlReader productsReader = null;
StringBuilder productList = new StringBuilder();
try
{
productsReader = dbSQL.ExecuteXmlReader(dbCommand);
// Iterate through the XmlReader and put the data into our results.
while (!productsReader.EOF)
{
if (productsReader.IsStartElement())
{
productList.Append(productsReader.ReadOuterXml());
productList.Append(Environment.NewLine);
}
}
}
finally
{
// Close the Reader.
if (productsReader != null)
{
productsReader.Close();
}
// Explicitly close the connection. The connection is not closed
// when the XmlReader is closed.
if (dbCommand.Connection != null)
{
dbCommand.Connection.Close();
}
}
return productList.ToString();
}
使用事务
{
bool result = false;
// Create the Database object, using the default database service. The
// default database service is determined through configuration.
Database db = DatabaseFactory.CreateDatabase();
// Two operations, one to credit an account, and one to debit another
// account.
string sqlCommand = "CreditAccount";
DbCommand creditCommand = db.GetStoredProcCommand(sqlCommand);
db.AddInParameter(creditCommand, "AccountID", DbType.Int32, sourceAccount);
db.AddInParameter(creditCommand, "Amount", DbType.Int32, transactionAmount);
sqlCommand = "DebitAccount";
DbCommand debitCommand = db.GetStoredProcCommand(sqlCommand);
db.AddInParameter(debitCommand, "AccountID", DbType.Int32, destinationAccount);
db.AddInParameter(debitCommand, "Amount", DbType.Int32, transactionAmount);
using (DbConnection connection = db.CreateConnection())
{
connection.Open();
DbTransaction transaction = connection.BeginTransaction();
try
{
// Credit the first account
db.ExecuteNonQuery(creditCommand, transaction);
// Debit the second account
db.ExecuteNonQuery(debitCommand, transaction);
// Commit the transaction
transaction.Commit();
result = true;
}
catch
{
// Rollback transaction
transaction.Rollback();
}
connection.Close();
return result;
}
}
三.常见功能
1.创建Database对象
创建一个默认的Database对象
默认的数据库在配置文件中:
创建一个实例Database对象
// which is determined by configuration information.
Database myDb = DatabaseFactory.CreateDatabase("DataAccessQuickStart");
创建一个具体的类型的数据库对象
SqlDatabase dbSQL = DatabaseFactory.CreateDatabase("DataAccessQuickStart") as SqlDatabase;
2.创建DbCommand对象
静态的SQL语句创建一个DbCommand
string sqlCommand = "Select CustomerID, LastName, FirstName From Customers";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
存储过程创建一个DbCommand
DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory");
3.管理对象
当连接对象打开后,不需要再次连接
string sqlCommand = "Select ProductID, ProductName From Products";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
// No need to open the connection; just make the call.
DataSet customerDataSet = db.ExecuteDataSet(dbCommand);
使用Using及早释放对象
DbCommand dbCommand = db.GetSqlStringCommand("Select Name, Address From Customers");
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
// Process results
}
4.参数处理
Database类提供了如下的方法,用于参数的处理:
AddParameter. 传递参数给存储过程
AddInParameter. 传递输入参数给存储过程
AddOutParameter. 传递输出参数给存储过程
GetParameterValue. 得到指定参数的值
SetParameterValue. 设定参数值
使用示例如下:
string sqlCommand = "GetProductDetails";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);
db.AddInParameter(dbCommand, "ProductID", DbType.Int32, 5);
db.AddOutParameter(dbCommand, "ProductName", DbType.String, 50);
db.AddOutParameter(dbCommand, "UnitPrice", DbType.Currency, 8);
DbCommand insertCommand = db.GetStoredProcCommand("AddProduct");
db.AddInParameter(insertCommand, "ProductName", DbType.String, "ProductName", DataRowVersion.Current);
db.AddInParameter(insertCommand, "CategoryID", DbType.Int32, "CategoryID", DataRowVersion.Current);
db.AddInParameter(insertCommand, "UnitPrice", DbType.Currency, "UnitPrice", DataRowVersion.Current);
四.使用场景
DAAB2.0是对ADO.NET2.0的补充,它允许你使用相同的数据访问代码来支持不同的数据库,您通过改变配置文件就在不同的数据库之间切换。目前虽然只提供SQLServer和Oracle的支持,但是可以通过GenericDatabase和ADO.NET 2.0下的DbProviderFactory对象来增加对其他数据库的支持。如果想要编写出来的数据库访问程序具有更好的移植性,则DAAB2.0是一个不错的选择,但是如果您想要针对特定数据库的特性进行编程,就要用ADO.NET了。
参考:Enterprise Libaray –January 2006帮助文档及QuickStart
转载于:https://www.cnblogs.com/Terrylee/archive/2006/03/14/350026.html
Enterprise Library2.0(1):Data Access Application Block学习相关推荐
- Enterprise Library v5.0 -- Data Access Application Block 开发向导(3)
微软企业库 Enterprise Library 5.0 正式发布!!! Enterprise Library 5.0 开发向导- 简介(1) Enterprise Library v5.0 -- D ...
- Enterprise Library: Data Access Application Block配置文件分析篇
Enterprise Library: Data Access Application Block配置文件分析篇 Enterprise Library提供了Configuration Console配 ...
- [翻译]The Data Access Application Block
Enterprise Library 4.1 - October 2008 The Data Access Application Block 数据访问应用块 The Enterprise Libra ...
- 感觉 Data Access Application Block(DAAB) 里也有可能写得不太好的地方
昨天下载了博客园的代码,里面有一个 Data\SqlServer.cs 我不清楚是不是 MS DAAB 里的原样文件.不过前面有声明如下: // =========================== ...
- 开发自己的Data Access Application Block[下篇]
上接:[原创] 我的ORM: 开发自己的Data Access Application Block - Part I 4. Database 下面来介绍重中之重:Database,绝大部分的Data ...
- EntLib 3.1学习笔记(2) : Data Access Application Block
EntLib 3.1学习笔记(2) : Data Access Application Block 简化实现通用数据访问功能的开发任务.应用程序可以在很多情况下使用应用程序块,例如读取显示数据.获得通 ...
- Microsoft Enterprise Library 5.0 系列(五) Data Access Application Block
企业库数据库访问模块通过抽象工厂模式,允许用户通过简单的配置选择不同的数据库作为程序的数据源,大大解决了切换数据库时带来的麻烦.因为我本机只安装了SQL Server 2005,所以在此只做SQL的演 ...
- Enterprise Library2.0研究(一)日志组件的使用场景
Enterprise Library2.0刚刚发布了December 2005的release,多了configuration的工具,真是及时,就不用自己做了.被安排看日志这一块,就开始翻译官方的do ...
- 微软模式与实践团队发布Enterprise Library 4.1及Unity Application Block 1.2
微软模式与实践团队发布Enterprise Library 4.1及Unity Application Block 1.2,具体可参看InfoQ的新闻http://www.infoq.com/cn/n ...
- Microsoft Enterprise Library 5.0 系列(十) Configuration Application Block
到目前为止,我们使用的模块都是在同一个配置文件中,这显然是不灵活的,我们希望每个功能模块能独立的在一个配置文件中体现,这样不仅易于管理,易于扩展,也易于阅读和分类.企业库当然考虑到了这个问题并且提供了 ...
最新文章
- mysql为什么要压测_mysql集群压测的详细介绍
- Linux命令-安装zip和unzip命令
- 前沿 | 一文详解自动驾驶激光雷达和摄像头的数据融合方法
- Tomcat服务在Eclipse中能够正常启动,但页面出现404错误的解决方法
- python爬虫怎么爬小说_python从爬虫基础到爬取网络小说实例
- Windows系统下oracle数据库每天定时备份
- python中的数学模块
- getter方法的作用 vuex_Vuex的工作流程
- php注册树模式,PHP设计模式之注册树模式
- Java新职篇:一维数组
- php 同义词词库,php如何实现同义词替换
- 【常用办公软件有那些】万彩办公大师教程丨屏幕放大镜的使用
- KC伺服舵机带参四方向Demo程序
- 顶级摄影师的磨皮美白利器Portraiture,支持搭配微设证件大师使用
- 苹果c语言怎么用windows。h_苹果12怎么用蓝牙传照片?iphone12无线传相片的详细步骤...
- 完整版《贴心萌宝荒唐爹》小说全文阅读
- 整数 (Integer)
- 基于微信小程序的宿舍管理平台
- Docker数据卷—Volumes
- acm暑期集训_2020.07.02
热门文章
- Educational Codeforces Round 7
- JMS学习十一(ActiveMQ Consumer高级特性之独有消费者(Exclusive Consumer))
- vue开发中v-for在Eslint的规则检查下出现:Elements in iteration expect to have 'v-bind:key' directives...
- 篮球30秒可控计时器
- oracle PL/SQL(procedure language/SQL)程序设计之异常(exception)
- 【玩转开源】BananaPi R2——移植RPi.GPIO 到 R2
- DHCP中继数据包互联网周游记
- 《Asp.Net 2.0 揭秘记(十四)
- 线性查找算法(BFPRT)
- 深入Jetty源码之HttpGenerator