Data Access Application Block QuickStart 的详细使用过程
首先是建立数据库。这是我的sql脚本。
go
create database DataAccessTest
go
use DataAccessTest
go
create table [Students] -- 学生
(
[SerialNumber] int identity(1,1) primary key, -- 唯一标识
[SID] nvarchar(50), -- 学号
[SName] nvarchar(50) , -- 姓名
[SClass] nvarchar(50) -- 班级
)
go
insert into [Students]([SID], [SName], [SClass]) values ('06130001', 'Jim Carry', 'CET Band 4')
insert into [Students]([SID], [SName], [SClass]) values ('06130002', '龌龊男', 'CET Band 4')
insert into [Students]([SID], [SName], [SClass]) values ('06130003', 'dudu', 'CET Band 4')
insert into [Students]([SID], [SName], [SClass]) values ('06130004', '猥琐男', 'CET Band 6')
insert into [Students]([SID], [SName], [SClass]) values ('06130005', '章朝阳', 'CET Band 6')
go
create procedure [GetStudentsByClass]
(
@SClass nvarchar(50)
)
as
select * from [Students] where [SClass] = @SClass
go
create procedure [AddStudent]
(
@SID nvarchar(50),
@SName nvarchar(50),
@SClass nvarchar(50)
)
as
insert into [Students]([SID], [SName], [SClass]) values (@SID, @SName, @SClass)
select * from [Students] where [SerialNumber] = SCOPE_IDENTITY()
go
create procedure [DeleteStudent]
(
@SerialNumber int
)
as
delete from [Students] where [SerialNumber] = @SerialNumber
go
create procedure [UpdateStudent]
(
@SerialNumber int,
@SID nvarchar(50),
@SName nvarchar(50),
@SClass nvarchar(50)
)
as
update [Students] set [SID] = @SID, [SName] = @SName, [SClass] = @SClass where [SerialNumber] = @SerialNumber
select * from [Students] where [SerialNumber] = @SerialNumber
go
create procedure [GetStudent]
(
@SerialNumber int,
@SID nvarchar(50) output,
@SName nvarchar(50) output,
@SClass nvarchar(50) output
)
as
select @SID = [SID], @SName = [SName], @SClass = [SClass] from [Students] where [SerialNumber] = @SerialNumber
go
create procedure [GetStudentName]
(
@SerialNumber int
)
as
select [SName] from [Students] where [SerialNumber] = @SerialNumber
go
这里使用的是sql server 2005 express edition。这里有一个东西需要注意一下:在UpdateStudent存储过程中在update语句执行完成之后又紧跟了一句select语句,在微软提供的源代码中对这种行为有一行注释:This statement is used to update the DataSet if changes are done on the updated record (identities, timestamps or triggers )。好像是说这条语句是来在被更新的数据又被更新之后来更新DataSet的,呵呵,好多更新,没太明白,请高人指点一下嘻嘻。
建立了数据库之后,为了简单,我建立了一个console application。然后在项目中添加了一个app.config文件。这还是我第一次使用app.config呢!以前一直都是做web开发的嘻嘻。文件如下:
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />
</configSections>
<connectionStrings>
<add name="DataAccessTest" providerName="System.Data.SqlClient" connectionString="server=.\sqlexpress;database=DataAccessTest;Integrated Security=true" />
</connectionStrings>
<dataConfiguration defaultDatabase="DataAccessTest" />
</configuration>
在这里首先注册了一个配置段,对应于DatabaseSettings类型。就是说配置文件下面的dataConfiguration部分要用DatabaseSettings类来处理,至于怎么处理,不知道。希望在分析了源代码之后能够了解。接下来dataConfiguration的defaultDatabase属性的内容如果我没猜错的话应该是上面的connectionString,就是说默认的数据库是通过ConnectionString来指定的。在后面声明数据库的时候也可以指定数据库名,这里猜测可能就是ConnectionString,不过我没有测试。
在创建了app.config之后要添加引用。在我的项目中使用Data Access Application Block的时候要添加两个引用:Microsoft.Practices.EnterpriseLibrary.Common.dll和Microsoft.Practices.EnterpriseLibrary.Data.dll,至于其它时候是不是需要添加别的引用,还是不知道。这两个文件可以在安装Microsoft Enterprise Library January 2006路径的bin文件夹中找到。
接下来开始正式写代码了。在微软的样例中一共提供了六种应用情况,但是后两种应用(事务支持和利用sql server返回xml,只能应用于sql server)我从来都没有使用过,所以就没有实现。感兴趣的话可以自己看看嘻嘻。
第一个函数是使用DataReader直接返回数据的例子,也是我平时最长使用的方法。代码如下:
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand("select * from Students");
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
while (reader.Read())
{
Console.WriteLine("SN:{0} ID:{1} Name:{2}\t Class:{3}", reader[0], reader[1], reader[2], reader[3]);
}
}
}
这里使用了工厂模式生成数据库对象,还使用了全新的DbXXX对象。这些东西都是我很感兴趣的,不过因为开窍时间比较晚,暂时对他们还没有什么认识,希望以后能好好研究一下。另外我在前面说可以在创建数据库的时候指定ConnectionString,就是指在DatabaseFactory.CreateDatabase()时可以传递一个string类型的参数,估计就是你所想指定的ConnectionString。剩下的部分没有什么差别了,只不过使用的方法和ado.net不是很一样。
接下来是使用存储过程的例子:
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetStudentsByClass");
db.AddInParameter(dbCommand, "SClass", DbType.String, "CET Band 4");
DataSet band4Students = db.ExecuteDataSet(dbCommand);
foreach (DataRow row in band4Students.Tables[0].Rows)
{
Console.WriteLine("SN:{0} ID:{1} Name:{2}\t Class:{3}", row[0], row[1], row[2], row[3]);
}
}
这里通过AddInParameter方法向指定的DbCommand对象加入参数。接下来的代码就没有什么值得说的部分了,一起贴出来。
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
namespace DataAccessTest
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press \"enter\" to run IDataReader & direct sql string demo:");
Console.ReadLine();
Console.WriteLine();
PrintAllStudents();
Console.WriteLine();
Console.Write("Press \"enter\" to run DataSet & stored procedure demo:");
Console.ReadLine();
Console.WriteLine();
GetCETBand4Students();
Console.WriteLine();
Console.Write("Press \"enter\" to run updating with DataSet demo:");
Console.ReadLine();
Console.WriteLine();
UpdateWithDataSet();
Console.WriteLine();
Console.Write("Press \"enter\" to run output parameter demo:");
Console.ReadLine();
Console.WriteLine();
OutputParameter();
Console.WriteLine();
Console.Write("Press \"enter\" to run ExecuteScalar demo:");
Console.ReadLine();
Console.WriteLine();
ExecuteScalar();
Console.WriteLine();
Console.WriteLine("All demos finished, press\"enter\" to exit.");
Console.ReadLine();
}
static void PrintAllStudents()
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand("select * from Students");
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
while (reader.Read())
{
Console.WriteLine("SN:{0} ID:{1} Name:{2}\t Class:{3}", reader[0], reader[1], reader[2], reader[3]);
}
}
}
static void GetCETBand4Students()
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetStudentsByClass");
db.AddInParameter(dbCommand, "SClass", DbType.String, "CET Band 4");
DataSet band4Students = db.ExecuteDataSet(dbCommand);
foreach (DataRow row in band4Students.Tables[0].Rows)
{
Console.WriteLine("SN:{0} ID:{1} Name:{2}\t Class:{3}", row[0], row[1], row[2], row[3]);
}
}
static void UpdateWithDataSet()
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand("select * from Students");
DataSet students = new DataSet();
db.LoadDataSet(dbCommand, students, "Students");
students.Tables[0].Rows.Add(new object[] { DBNull.Value, "06130006", "tel1sen", "CET Band 2" });
students.Tables[0].Rows[0]["SClass"] = "CET Band 8";
DbCommand insertCommand = db.GetStoredProcCommand("AddStudent");
db.AddInParameter(insertCommand, "SID", DbType.String, "SID", DataRowVersion.Current);
db.AddInParameter(insertCommand, "SName", DbType.String, "SName", DataRowVersion.Current);
db.AddInParameter(insertCommand, "SClass", DbType.String, "SClass", DataRowVersion.Current);
DbCommand deleteCommand = db.GetStoredProcCommand("DeleteStudent");
db.AddInParameter(deleteCommand, "SerialNumber", DbType.Int32, "SerialNumber", DataRowVersion.Current);
DbCommand updateCommand = db.GetStoredProcCommand("UpdateStudent");
db.AddInParameter(updateCommand, "SerialNumber", DbType.Int32, "SerialNumber", DataRowVersion.Current);
db.AddInParameter(updateCommand, "SID", DbType.String, "SID", DataRowVersion.Current);
db.AddInParameter(updateCommand, "SName", DbType.String, "SName", DataRowVersion.Current);
db.AddInParameter(updateCommand, "SClass", DbType.String, "SClass", DataRowVersion.Current);
Console.WriteLine("Rows affected:{0}", db.UpdateDataSet(students, "Students", insertCommand, updateCommand, deleteCommand, UpdateBehavior.Standard));
PrintAllStudents();
}
static void OutputParameter()
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetStudent");
db.AddInParameter(dbCommand, "SerialNumber", DbType.Int32, 1);
db.AddOutParameter(dbCommand, "SID", DbType.String, 50);
db.AddOutParameter(dbCommand, "SName", DbType.String, 50);
db.AddOutParameter(dbCommand, "SClass", DbType.String, 50);
db.ExecuteNonQuery(dbCommand);
Console.WriteLine("SN:{0} ID:{1} Name:{2}\t Class:{3}", db.GetParameterValue(dbCommand, "SerialNumber"), db.GetParameterValue(dbCommand, "SID"), db.GetParameterValue(dbCommand, "SName"), db.GetParameterValue(dbCommand, "SClass"));
}
private static void ExecuteScalar()
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetStudentName", 1);
Console.WriteLine("Name:{0}", db.ExecuteScalar(dbCommand));
}
}
}
当然这只是Data Access Application Block的一个极其简单的应用,而且Data Access Application Block的使用方法远不止于此
这篇文章是从博客园:骑士的荣誉 看到的,虽然简单,确实入门兄弟的上等参考,顾贴一下