微软企业库之数据访问模块基本使用
来源:互联网 发布:扎金花闷牌算法 编辑:程序博客网 时间:2024/05/05 23:58
工作的关系需要熟悉微软企业库。转载一些有用的教程和笔记以供自己和大家参考。附:原文链接。
微软企业库的数据访问模块封装了操作数据库的若干方法,本文基于微软企业库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());
}
}
- 微软企业库之数据访问模块基本使用
- 微软企业库-数据访问
- 微软企业库4.1学习笔记(三十二)数据访问模块 在应用中使用数据访问模块
- 微软企业库5.0学习笔记(三十三)数据访问模块
- 使用微软企业库中数据模块完成事务操作
- 微软企业库5.0学习笔记(三十四)数据访问模块 各种获取数据的方式
- 微软企业库4.1学习笔记(三十一)数据访问模块 简介
- 微软企业库5.0学习笔记(三十五)数据访问模块 DataSet以及数据库事务
- 使用微软企业库构建简单的数据访问层,供新人参考(C#+SqlServer)
- 微软企业库缓存使用
- 微软企业库的使用
- 微软企业库5.0 学习之路——基本入门
- 微软企业库中DbDataAdapter使用
- 企业库之数据访问的一个小应用
- 微软企业库4.1学习笔记(十四)缓存模块2 使用缓存模块进行开发
- 微软企业库4.1学习笔记(三十七)日志模块 在应用中使用日志模块
- 微软企业库4.1学习笔记(十五)缓存模块3 使用数据库作为后端存储
- 微软企业库4.1学习笔记(十六)缓存模块4 服务器场中的缓存使用
- Android Handler详解
- 条码扫描二维码扫描——ZXing android 源码简化
- CSS伪类伪元素
- JSF中使用a4j:commandButton和a4j:jsFunction实现校验,操作后刷新
- Android上玩玩Hook:Cydia Substrate实战
- 微软企业库之数据访问模块基本使用
- Xamarin.Forms教程下载安装Xamarin.iOS
- Android—SVN部署
- tcp还是udp,这是个大问题!
- Spring Web Flow 2.0 入门
- CoAP学习笔记——IETF文档和draft文档
- 关于'for' loop initial declaration used outside C99 mode的说明
- Bitnami提供Gitlab虚拟机中ssh开启
- UIPickerView