Enterprise Library v5.0 -- Data Access Application Block 开发向导(2)

Data Access 应用程序块是最常用的Application block之一,因为它可以更容易地实现大多数数据访问操作,不必重复编写数据访问代码,甚至不必关心应用程序的数据库。如果使用DAAB,你可以很容易转换应用程序使用不同的数据库,不必重写代码、编译和部署。管理员可以更改目标数据库到不同的服务器,甚至到不同的数据库类型(如SQL Server或Oracle等等)。DAAB包含了SQL Server、SQL Server Compact Edition 和Oracle数据库提供程序。
 
DAAB 能够做什么?
DAAB抽象了实际使用的数据库,暴露了一系列方法,更容易访问数据库,完成通用的任务。例如,你可简单创建一个合适的Database类实例,然后使用该对象获取一个合适的Command实例,接着传递给Database类的ExecuteDataSet方法,最终得到一个DataSet对象。你不必创建DataAdapter或者调用Fill方法。ExecuteDataSet方法管理数据库连接,并执行填充DataSet的所有任务。相同地,也可以通过Database类获得DataReader对象。
 
如何使用DAAB?
首先需要添加DAAB 的程序集,配置需要访问的数据库,添加其他相关的程序集到项目中。接着创建数据库对象实例,并读取和操作数据。
 
创建数据库对象实例
可以使用多种方法获取想访问的Database 实例。下面的范例代码通过调用EnterpriseLibraryContainer的静态属性Current的GetInstance方法,来获得Database实例。
        static Database defaultDB = null;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            // Resolve the default Database object from the container.
            // The actual concrete type is determined by the configuration settings.
            defaultDB = EnterpriseLibraryContainer.Current.GetInstance<Database>();
        }
 
上述代码演示了如何获取默认数据库的实例。当然,也可使用连接字符串(Connection string)的名称,来获取命名的数据库实例。
static Database namedDB = null;
// Resolve a Database object from the container using the connection string name.
namedDB = EnterpriseLibraryContainer.Current.GetInstance<Database>("ExampleDatabase");
 
上述代码引用了Database基类的实例,其中一些功能仅仅适用于具体的数据库类型。如ExecuteXmlReader方法仅仅适用于SqlDatabase类。如果你想使用这一功能,你必须转换数据库类型为具体的类型。如下范例代码创建一个SqlDatabase对象实例。
static SqlDatabase sqlServerDB = null;
// Resolve a SqlDatabase object from the container using the default database.
sqlServerDB = EnterpriseLibraryContainer.Current.GetInstance<Database>() as SqlDatabase;
 
读取多条数据记录
简单的查询包含一个SQL语句或一个存储过程,不接收参数,执行ExecuteReader方法。如下代码演示一个简单的调用存储过程的方法,你可以忽略CommandType参数,默认为CommandType.StoredProcedure(在ADO.NET中,默认为CommandType.Text)。
// Call the ExecuteReader method by specifying just the stored procedure name.
using (IDataReader reader = namedDB.ExecuteReader("MyStoredProcName"))
{
// Use the values in the rows as required.
}
 
如果使用SQL脚本,则必须指定CommandType参数,如下所示。
// Call the ExecuteReader method by specifying the command type
// as a SQL statement, and passing in the SQL statement.
using (IDataReader reader = namedDB.ExecuteReader( CommandType.Text ,
"SELECT TOP 1 * FROM OrderList"))
{
// Use the values in the rows as required ‐ here we are just displaying them.
DisplayRowValues(reader);
}
private static void DisplayRowValues(IDataReader reader)
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine("{0} = {1}", reader.GetName(i), reader[i].ToString());
}
Console.WriteLine();
}
}
 
输出结果为数据列和相对应的字段值列表,如下所示。
Id = 1
Status = DRAFT
CreatedOn = 01/02/2009 11:12:06
Name = Adjustable Race
LastName = Abbas
FirstName = Syed
ShipStreet = 123 Elm Street
ShipCity = Denver
ShipZipCode = 12345
ShippingOption = Two‐day shipping
State = Colorado
 
使用参数数组读取多条数据记录
上述范例代码演示了不带参数的存储过程和SQL语句,然而在多数情况下,我们需要采用接收传入参数的查询。如果你仅仅使用传入参数,可以包裹传入参数为Object数组,并传递给存储过程或SQL语句。注意,必须按照查询需要的参数次序,将参数值添加到数组中 – 你仅仅需要提供实际的参数值。如下范例代码演示如何传入一个字符串参数给存储过程。
// Call the ExecuteReader method with the stored procedure
// name and an Object array containing the parameter values.
using (IDataReader reader = defaultDB.ExecuteReader("ListOrdersByState",
new object[] { "Colorado" }))
{
// Use the values in the rows as required ‐ here we are just displaying them.
DisplayRowValues(reader);
}
 
使用带命名参数的查询,读取多条数据记录
上述带参数值数组的范例代码简单且有效,但是有一些限制。首先,它不支持你指定参数的方向(如输入或输出),或数据类型 – 如传入参数的数据类型不完全匹配(或者不能隐式转化)存储过程的参数类型,将发生错误。
 
为了使用命名参数或定义类型的参数,你必须访问Command对象,该对象用来执行查询,并操作参数集合。DAAB通过Database类提供GetSqlStringCommand 和 GetStoredProcCommand 方法,使创建和访问 Command 对象更加容易。这些方法为配置的数据库返回一个合适的Command实例。
 
在创建好合适的Command实例之后,你可使用Database类的大量方法来操作参数集合。如使用AddInParameter或AddOutParameter方法,添加特定方向的参数。或者使用AddParameter方法,且带ParameterDirection参数值。你可以使用GetParameterValue和SetParameterValue方法,更改已经加入到Command实例的参数值。
 
下面范例代码演示如何轻松创建Command实例,添加输入参数,并执行SQL语句和存储过程。注意Database类添加参数到Command实例,包括参数名、数据类型和参数值。
// Read data with a SQL statement that accepts one parameter.
string sqlStatement = "SELECT TOP 1 * FROM OrderList WHERE State LIKE @state";
// Create a suitable command type and add the required parameter.
using (DbCommand sqlCmd = defaultDB.GetSqlStringCommand(sqlStatement))
{
defaultDB. AddInParameter(sqlCmd, "state", DbType.String, "New York");
// Call the ExecuteReader method with the command.
using (IDataReader sqlReader = namedDB.ExecuteReader(sqlCmd))
{
Console.WriteLine("Results from executing SQL statement:");
DisplayRowValues(sqlReader);
}
}
// Now read the same data with a stored procedure that accepts one parameter.
string storedProcName = "ListOrdersByState";
// Create a suitable command type and add the required parameter.
using (DbCommand sprocCmd = defaultDB.GetStoredProcCommand(storedProcName))
{
defaultDB. AddInParameter(sprocCmd, "state", DbType.String, "New York");
// Call the ExecuteReader method with the command.
using (IDataReader sprocReader = namedDB.ExecuteReader(sprocCmd))
{
Console.WriteLine("Results from executing stored procedure:");
DisplayRowValues(sprocReader);
}
}

转载于:https://www.cnblogs.com/Rising/archive/2010/06/22/1762807.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值