Maison > Article > base de données > 黄聪:Microsoft Enterprise Library 5.0 系列教程(五) Data Acc
企业库数据库访问模块通过抽象工厂模式 , 允许用户通过简单的配置选择不同的数据库作为程序的数据源 , 大大解决了切换数据库时带来的麻烦 . 因为我本机只安装了 SQL Server 2005, 所以在此只做 SQL 的演示 , 需要深究的朋友可以访问以下网站 : http://msdn.m
企业库数据库访问模块通过抽象工厂模式,允许用户通过简单的配置选择不同的数据库作为程序的数据源,大大解决了切换数据库时带来的麻烦.因为我本机只安装了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语句:
///
/// 执行ExecuteNonQuery
///
privatevoid ExecuteNonQuery_Click(object sender, EventArgs e)
{
db.ExecuteNonQuery(CommandType.Text, "INSERT INTO [College] ([CollegeID],[Name]) values (6,'体育学院')");
}
(2) 执行ExecuteDataSet,返回DataSet类型的数据集.
///
/// 执行ExecuteDataSet,返回College列表
///
///
privatevoid ExecuteDataSet_Click(object sender, EventArgs e)
{
string sql ="select * from College";
DbCommand dw = db.GetSqlStringCommand(sql);
dataGridView1.DataSource = db.ExecuteDataSet(dw).Tables[0];
}
(3) 执行ExecuteScalar,返回第一行第一列的值.
///
/// 执行ExecuteScalar,返回第一行第一列的值
///
///
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) 执行存储过程.
///
/// 执行存储过程
///
privatevoid StoredProcCommand_Click(object sender, EventArgs e)
{
DbCommand dc = db.GetStoredProcCommand("usp_College_LoadByID");
db.AddInParameter(dc, "@CollegeID", System.Data.DbType.Int32, 5);
dataGridView1.DataSource = db.ExecuteDataSet(dc).Tables[0];
}
(5) 通过代码实现事务.
///
/// 事务
///
privatevoid Transaction_Click(object sender, EventArgs e)
{
DbCommand dc1 = db.GetStoredProcCommand("usp_College_Insert");
db.AddInParameter(dc1, "@CollegeID", DbType.Int32, 7);
db.AddInParameter(dc1, "@Name", DbType.String, "文旅学院");
DbCommand dc2 = db.GetStoredProcCommand("usp_College_Insert");
db.AddInParameter(dc2, "@CollegeID", DbType.Int32, 7);
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更新数据库.
///
/// 通过DataSet更新数据库
///
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[] { 8, "外国语学院" });
//修改一个原有数据
dTable.Rows[0]["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化.
///
/// 返回值XML化
///
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");
IEnumerablestring> 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) 将返回的数据对象化.
///
/// DataAsObject
///
privatevoid DataAsObject_Click(object sender, EventArgs e)
{
//将返回的数据对象化
var results = db.ExecuteSprocAccessorCollege>("usp_College_LoadAll");
MessageBox.Show(results.ElementAt(0).ToString());
}
(9) 异步访问数据库.
///
/// 异步访问数据库
///
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, 1);
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[0], (string)reader[1]);
MessageBox.Show(c.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}