介紹了微軟企業庫之數據訪問模塊的基本使用。
微軟企業庫的數據訪問模塊封裝了操作資料庫的若幹方法,本文基於微軟企業庫5.0。
1、添加程式集引用
需要在項目中添加對Microsoft.Practices.EnterpriseLibrary.Common.dll以及Microsoft.Practices.EnterpriseLibrary.Data.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());
}
}