Rickie is back .... 人生·工作的结果=思维方式×热情×能力

今天比昨天更好,明天比今天更好,为此,不屈不挠地工作、勤勤恳恳地经营、孜孜不倦地修炼,我们人生的目的和价值就是这样确确实实地存在着。

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  397 随笔 :: 3 文章 :: 1310 评论 :: 129 引用

Enterprise Library: Data Access Application Block使用向导
Part 2
 

Written by: Rickie Lee (rickieleemail#yahoo.com)

My blog:http://www.cnblogs.com/rickie

本文是前一篇posting《Enterprise Library: Data Access Application Block使用向导,Part 1》的Part 2,主要演示使用Data Access Application Block (Enterprise Library)的代码部分。

Data Access Application Block使用向导:

1.增加对Microsoft.Practices.EnterpriseLibrary.Data.dllMicrosoft.Practices.EnterpriseLibrary.Configuration.dll的引用,并在代码在添加:

using Microsoft.Practices.EnterpriseLibrary.Data;

 

2.调用代码示例:

(1) ExecuteDataSet方法

Database db = DatabaseFactory.CreateDatabase();

DataSet dsCustomers = db.ExecuteDataSet(CommandType.Text, "Select * From Customers" );

customerGrid.DataSource = dsCustomers.Tables[0];

 

(2) ExecuteReader方法

Database db = DatabaseFactory.CreateDatabase();

 

string sqlCommand = "Select top 5 * From Customers";

DBCommandWrapper dbCommandWrapper = db.GetSqlStringCommandWrapper(sqlCommand);

 

StringBuilder readerData = new StringBuilder();

 

using (IDataReader dataReader = db.ExecuteReader(dbCommandWrapper))

{

while (dataReader.Read())

{

readerData.Append(dataReader["ContactName"]);

readerData.Append(Environment.NewLine);

}

}

 

txtResult.Text = readerData.ToString();

为了执行SQL语句,上述代码使用GetSqlStringCommandWrapper方法创建合适command wrapper对象,然后作为参数传递给ExecuteReader方法。

 

(3) ExecuteNonQuery方法

Database db = DatabaseFactory.CreateDatabase();

 

string sqlCommand = "getProductDetails";

DBCommandWrapper dbCommandWrapper = db.GetStoredProcCommandWrapper(sqlCommand);

 

// Add paramters

int productID=1;

// Input parameters can specify the input value

dbCommandWrapper.AddInParameter("@ProductID", DbType.Int32, productID);

// Output parameters specify the size of the return data

dbCommandWrapper.AddOutParameter("@ProductName", DbType.String, 40);

dbCommandWrapper.AddOutParameter("@UnitPrice", DbType.Currency, 8);

dbCommandWrapper.AddOutParameter("@QtyPerUnit", DbType.String, 20);

 

db.ExecuteNonQuery(dbCommandWrapper);

 

// Row of data is captured via output parameters

string results = string.Format(CultureInfo.CurrentCulture, "{0}, {1}, {2:C}, {3} ",

      dbCommandWrapper.GetParameterValue("@ProductID"),

      dbCommandWrapper.GetParameterValue("@ProductName"),

      dbCommandWrapper.GetParameterValue("@UnitPrice"),

      dbCommandWrapper.GetParameterValue("@QtyPerUnit"));

 

txtResult.Text = results;

为了执行存储过程,上述代码使用GetStoredProcCommandWrapper方法创建合适的command wrapper对象,然后作为参数传递给ExecuteNonQuery方法。

 

(4) ExecuteScalar方法

Database db = DatabaseFactory.CreateDatabase();

 

string sqlCommand = "GetProductName";

int productID=1;

DBCommandWrapper dbCommandWrapper = db.GetStoredProcCommandWrapper(sqlCommand, productID);

 

// Retrieve ProdcutName. ExecuteScalar returns an object, so

// we cast to the correct type (string).

string productName = (string) db.ExecuteScalar(dbCommandWrapper);

 

txtResult.Text = productName;

 

Demo程序界面如下(注意在项目属性窗口中设置Post-build Event Command Line属性值:copy "$(ProjectDir)*.config" "$(TargetDir)"):
Enterprise_DAABDemo.JPG

 

***

作者:Rickie Lee (rickieleemail#yahoo.com)

本文参考Enterprise Library: Data Access Application Block Quick Start范例,简单编写一个DEMO

 

References:

1. Enterprise Library: Data Access Application Block Quick Start

2. Rickie, Microsoft patterns & practices Enterprise Library January 2005 [中文稿], http://www.cnblogs.com/rickie/archive/2005/01/30/99443.html

3. Rickie, Enterprise Library released! http://www.cnblogs.com/rickie/archive/2005/01/29/99106.html

posted on 2005-02-06 03:26 Rickie 阅读(12553) 评论(30) 编辑 收藏

评论

原来EL使用了Configuration,缺省是从DataConnection.config中读取数据库连接信息,怪不得我不能让DAAB正常运行
 回复 引用 查看   

#2楼 2005-02-06 10:07 yoyo开发田地      
在一个应用中可能会用到好几个block,能不能把所有的配置文件写在一个config里?比如dataConfiguration,cacheConfiguration都写在一起。
 回复 引用 查看   

问得好,应该可以这样的。
 回复 引用 查看   

#4楼[楼主] 2005-02-06 16:29 Rickie      
As far as I know, I don't think we can write all configuration settings, such as dataConfiguration, cacheConfiguration, etc., into one configuration file via Configuration Console tool.
*
Even manully entering the configuration information, currently I have no idea about it.
 回复 引用 查看   

比如cache的config:
<?xml version="1.0" encoding="utf-8"?>
<cachingConfiguration>
<xmlSerializerSection type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching">
....
</xmlSerializerSection>
</cachingConfiguration>

又有data的config:
<?xml version="1.0" encoding="utf-8"?>
<dataConfiguration>
...
</dataConfiguration>

手工的话要如何放到一起?
我试着用一个父节点<root>去把这俩configuration放到一起,但系统却抛出找不到节点的异常.
 回复 引用 查看   

#6楼[楼主] 2005-02-06 18:47 Rickie      
Why do you want to merge these configuration settings into one configuraiton file?
*
If you really want to do it, maybe you have to change the source of the Configuration Application Block.
 回复 引用 查看   

你这个例子似乎我没有在quick starters中看见哦
 回复 引用 查看   

#8楼[楼主] 2005-02-07 03:43 Rickie      
Yes, this demo application is written by myself, which is not available in Enterprise Library Quick Starts.
*
There is a DAAB Quick Start provided by Enerprise Library.
 回复 引用 查看   

#9楼 2005-02-13 02:30 yuewah
If there are 2 DataBase Tables that has Parent-Child Relationship as well as the corresponding DataSet, Anyone know what is the best practise using the DAAB?
 回复 引用   

#10楼 2005-02-17 13:41 冰火      
可惜目前不支持access!
 回复 引用 查看   

#11楼[楼主] 2005-02-17 14:12 Rickie      
You can extend the application block by adding a new database type, AccessDatabase.
*
You can get more information to see Adding a New Database Provider section in CHM file.
 回复 引用 查看   

#12楼 2005-03-04 13:15 Bruse[未注册用户]
不知道怎么把Data Application Block应用到Web上面,还有怎么自己创建基于Access的Provider,请各位指教!
 回复 引用   

引用daab的dll就可以拉
 回复 引用 查看   

#14楼 2005-03-07 17:09 summer[未注册用户]
感觉没有单独用DataAccess Block简单、方便

如果用DataSqlReader
直接用
SqlDataReader dr=SqlHelper.ExecuteReader(business.myConn,CommandType.Text,strSql);
 回复 引用   

#15楼 2005-03-14 08:45 周奔驰
能说说DBCommandWrapper这个类的作用么
 回复 引用   

#16楼 2005-04-01 16:18 charlie
嗯,这个挺好的,省得写那么多重复代码
 回复 引用   

#17楼 2005-04-11 18:39 小牛哥
PerformanceCounterInstances类行230出现以下问题:

未处理的“System.Security.SecurityException”类型的异常出现在 mscorlib.dll 中。

其他信息: 不允许所请求的注册表访问权。

 回复 引用   

#18楼 2005-04-25 17:40 aa
在类似于智能客户端的程序上如何应用Application block?
how use Appliction block in smartclient?
 回复 引用   

#19楼 2005-05-10 11:51 大侠(cer)      
怎样不调用存贮过程往数据库内写内容啊?
如执行一条INSERT INTO tableName(colName) VALUES ('test')
语句呢?
 回复 引用 查看   

#20楼 2005-05-16 11:06 ziqi
How to use Enterprise Library in Web App? I just know the linchpin of this problem is the configuration of web.config.
The error is as follows: Invalid section name. The section 'dataConfiguration' does not exist in the requested configuration file 'c:/inetpub/wwwroot/ColorRingSvr/web.config' or the file 'c:\windows\microsoft.net\framework\v1.1.4322\Config\machine.config'. Make sure that the 'enterpriseLibrary.configurationSections' configuration section exists in one of the files and that the section 'dataConfiguration' is defined.
 回复 引用   

#21楼 2005-06-20 18:36 Ying-Shen Yu
http://blog.hishambaz.com/archive/2005/01/29/194.aspx

在Web Application 中使用Enterprise Lib Data Access Application Block,
1. use the configuration tool to do the required configurations
2. if you get SecurityException due to invalid registry access, you need to make sure if you have runned the
Install Service program , in
start->programs->Microsoft practices->Install Services.


 回复 引用   

#22楼 2005-09-30 15:56 zm[未注册用户]
Database db = DatabaseFactory.CreateDatabase();
这个在vs2003下没问题,在vs2005下就报错,我用的是2005六月版,什么问题?请教了, 能讲解以下,发到我的邮箱么?my2000@gmail.com

 回复 引用   

在执行 GetProductDetails 时,出现:

**************************************
????: EntLibQuickStarts.dbo.GetProductDetails
???? = 0
????:
@ProductName = Chai
@UnitPrice = 18.0000

**************************************

奇怪了。。怎么这样啊。。分析器里的中文是好好的啊。

******************************************************
DECLARE @RC int
DECLARE @ProductID int
DECLARE @ProductName nvarchar(50)
DECLARE @UnitPrice decimal(19,4)
SELECT @ProductID = 1
EXEC @RC = [EntLibQuickStarts].[dbo].[GetProductDetails] @ProductID, @ProductName OUTPUT , @UnitPrice OUTPUT
DECLARE @PrnLine nvarchar(4000)
PRINT '存储过程: EntLibQuickStarts.dbo.GetProductDetails'
SELECT @PrnLine = ' 返回代码 = ' + CONVERT(nvarchar, @RC)
PRINT @PrnLine
PRINT ' 输出参数: '
SELECT @PrnLine = ' @ProductName = ' + isnull( CONVERT(nvarchar, @ProductName), '<NULL>' )
PRINT @PrnLine
SELECT @PrnLine = ' @UnitPrice = ' + isnull( CONVERT(nvarchar, @UnitPrice), '<NULL>' )
PRINT @PrnLine

**************************************************

那位朋友帮忙下啊。。
 回复 引用   

#24楼 2006-01-12 16:23 程序人生      
dbCommandWrapper.AddOutParameter("@ProductName", DbType.String, 40);

dbCommandWrapper.AddOutParameter("@UnitPrice", DbType.Currency, 8);

dbCommandWrapper.AddOutParameter("@QtyPerUnit", DbType.String, 20);
还是不明白,
存储过程有输出参数名:那怎么对应
你程序怎么取值,
难道都是变量QtyPerUnit吗?
procedure SP_MONTH_CUT_PLAN(
A_YYYYMM IN DPS.MONTH_PROD_PLAN.YYYYMM%TYPE,
A_MESSAGE OUT VARCHAR2
)
AS

BEGIN
DBMS_OUTPUT.put_line('给'||A_YYYYMM||'月进行月计划制线平衡信息');
END;
如我上面的东西,怎么才能用C#做
public bool MonthInfo(string Month,out string A_MESSAGE)
{
try
{
Database DB = DatabaseFactory.CreateDatabase();
//运行存储过程名
string sqlCommandString = "DPS.PK_DAY_PACK_PLAN.SP_MONTH_PROD_PLAN";
DBCommandWrapper RunCommandWrapper = DB.GetStoredProcCommandWrapper(sqlCommandString);
RunCommandWrapper.AddInParameter("A_YYYYMM",DbType.String,Month);
RunCommandWrapper.AddOutParameter(":A_MESSAGE",DbType.String,2000 );
//加入存储过程的参数
DB.ExecuteNonQuery(RunCommandWrapper);

return true;
}
catch(Exception Error)
{
// MessageBox.Show(Error.Message,"错误信息");
A_MESSAGE ="";
return false;
}
}
 回复 引用 查看   

#25楼 2006-01-12 16:23 程序人生      
dbCommandWrapper.AddOutParameter("@ProductName", DbType.String, 40);

dbCommandWrapper.AddOutParameter("@UnitPrice", DbType.Currency, 8);

dbCommandWrapper.AddOutParameter("@QtyPerUnit", DbType.String, 20);
还是不明白,
存储过程有输出参数名:那怎么对应
你程序怎么取值,
难道都是变量QtyPerUnit吗?
procedure SP_MONTH_CUT_PLAN(
A_YYYYMM IN DPS.MONTH_PROD_PLAN.YYYYMM%TYPE,
A_MESSAGE OUT VARCHAR2
)
AS

BEGIN
DBMS_OUTPUT.put_line('给'||A_YYYYMM||'月进行月计划制线平衡信息');
END;
如我上面的东西,怎么才能用C#做
public bool MonthInfo(string Month,out string A_MESSAGE)
{
try
{
Database DB = DatabaseFactory.CreateDatabase();
//运行存储过程名
string sqlCommandString = "DPS.PK_DAY_PACK_PLAN.SP_MONTH_PROD_PLAN";
DBCommandWrapper RunCommandWrapper = DB.GetStoredProcCommandWrapper(sqlCommandString);
RunCommandWrapper.AddInParameter("A_YYYYMM",DbType.String,Month);
RunCommandWrapper.AddOutParameter(":A_MESSAGE",DbType.String,2000 );
//加入存储过程的参数
DB.ExecuteNonQuery(RunCommandWrapper);

return true;
}
catch(Exception Error)
{
// MessageBox.Show(Error.Message,"错误信息");
A_MESSAGE ="";
return false;
}
}
 回复 引用 查看   

#26楼 2006-04-06 16:36 jedliu[未注册用户]
to 程序人生:

从存储过程去参数可以用DBCommandWrapper的方法GetParameterValue
如:
wraper.GetParameterValue("@totalNumResult").ToString();

不知道你问的是不是这个意思?
 回复 引用   

#27楼 2006-04-06 16:37 jedliu[未注册用户]
我刚刚熟悉了这个东西。
不过感觉是好象比用平常的方法慢了许多。不知道各位朋友有没这种感觉?
 回复 引用   

#28楼 2006-04-24 01:31 卡卡.net      
在性能上面肯定不如直接来的快!所以EL适合用在企业级应用中.
 回复 引用 查看   

#29楼 2006-08-30 13:20 小新0574      
DBCommandWrapper 在 Enterprise Library - January 2006 是不是没有了,改用DbCommand代替了
 回复 引用 查看   

#30楼 2006-10-11 16:54 chatterley[匿名]
@小牛哥
你那问题解决了没有?到底是什么原因?
 回复 引用