微软企业库之数据访问模块基本使用
微软企业库的数据访问模块封装了操作数据库的若干方法,本文基于微软企业库5.0。
1、添加程序集引用
需要在项目中添加对下列程序集的引用
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll
2、使用命名空间
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
3、配置连接字符串
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=MySchool;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
4、主要方法
Database db = DatabaseFactory.CreateDatabase("ConnectionString");
4.1 执行增删改sql语句
public int Insert(Model.Subject model)
{
string sql = "insert into subject values(@subjectname,@hours,@gradeid)";
DbCommand cmd = db.GetSqlStringCommand(sql);
db.AddInParameter(cmd, "@subjectname", DbType.String, model.SubjectName);
db.AddInParameter(cmd, "@hours", DbType.Int32, model.Hours);
db.AddInParameter(cmd, "@gradeid", DbType.Int32, model.GradeId);
return db.ExecuteNonQuery(cmd);
}
4.2 返回第1行第1列的值
public int GetCount()
{
string sql = "select count(*) from subject";
DbCommand cmd = db.GetSqlStringCommand(sql);
return Convert.ToInt32(db.ExecuteScalar(cmd));
}
4.3 返回DataSet
public DataTable GetList()
{
string sql = "SELECT [SubjectId],[SubjectName],[Hours],[GradeName] from subject inner join grade on subject.GradeId=grade.GradeId";
DbCommand cmd = db.GetSqlStringCommand(sql);
DataSet ds = db.ExecuteDataSet(cmd);
return ds.Tables[0];
}
4.4 返回IDataReader
string sql = "select * from College where CollegeId=@id";
DbCommand cmd = db.GetSqlStringCommand(sql);
db.AddInParameter(cmd,"@id",DbType.Int32,id);
using (IDataReader dr = db.ExecuteReader(cmd))
{
if (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
4.5 执行存储过程
public int Delete(int subjectId)
{
string sql = "usp_DeleteSubject";
DbCommand cmd=db.GetStoredProcCommand(sql);
db.AddInParameter(cmd, "@subjectid", System.Data.DbType.Int32, subjectId);
return db.ExecuteNonQuery(cmd);
}
4.6 使用数据库事务
private void 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);
}
4.7 将返回的数据对象化
private void DataAsObject_Click(object sender, EventArgs e)
{
var results = db.ExecuteSprocAccessor<College>("usp_College_LoadAll");
MessageBox.Show(results.ElementAt(0).ToString());
}
4.8 异步执行(企业库中的异步访问数据库只支持SQL Server)
private void Async_Click(object sender, EventArgs e)
{
//创建新的数据库连接,属性必须添加:Asynchronous Processing=true
String connectionString = @"server=.\sqlexpress; 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());
}
}
//当获取完毕执行该函数
private void MyEndExecuteCallback(IAsyncResult result)
{
try
{
Database Sqldb = (Database)result.AsyncState;
IDataReader reader = db.EndExecuteReader(result);
if (reader.Read())
{
College c = new College((int)reader[0], (string)reader[1]);
MessageBox.Show(c.ToString());
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}