企業(yè)庫數(shù)據(jù)庫訪問模塊通過抽象工廠模式,允許用戶通過簡單的配置選擇不同的數(shù)據(jù)庫作為程序的數(shù)據(jù)源,大大解決了切換數(shù)據(jù)庫時帶來的麻煩.因為我本機(jī)只安裝了SQL Server 2005,所以在此只做SQL的演示,需要深究的朋友可以訪問以下網(wǎng)站:
http://msdn.microsoft.com/en-us/library/ff664408%28v=PandP.50%29.aspx
企業(yè)庫數(shù)據(jù)庫訪問模塊的幾大功能:
1. 最簡單的功能,通過ExecuteNonQuery.方法執(zhí)行SQL語句.
2. 執(zhí)行ExecuteDataSet,返回DataSet類型的數(shù)據(jù)集.
3. 執(zhí)行ExecuteScalar,獲取返回的第一行第一列的信息.
4. 執(zhí)行存儲過程.
5. 通過代碼實現(xiàn)事務(wù).
6. 通過DataSet更新數(shù)據(jù)庫.
7. 返回值XML化.
8. 將返回的數(shù)據(jù)對象化.
9. 異步訪問數(shù)據(jù)庫.
以上的功能我會在下面一一介紹,測試程序我已打包,大家可以點擊這里下載.
下面介紹如何使用Microsoft Enterprise Library 5.0中的數(shù)據(jù)庫訪問模塊.
1. 首先創(chuàng)建一個測試數(shù)據(jù)庫,創(chuàng)建數(shù)據(jù)庫的SQL文件我打包在壓縮包里了,大家可以點擊上面的下載鏈接下載.執(zhí)行完SQL文件后,可以看到我們創(chuàng)建好的TestDB數(shù)據(jù)庫:
2. 下載安裝好MicrosoftEnterprise Library 5.0,然后在運(yùn)行EntLibConfig.exe,選擇Blocks菜單 ,單擊 AddDatabase Settings .
3. 配置好文件之后保存為App.config文件,并添加到創(chuàng)建好的應(yīng)用程序中.并添加相應(yīng)的引用,在此我不再多講,大家下載我打包好的程序運(yùn)行即可看到
4. 下面來介紹我在應(yīng)用程序中實現(xiàn)的各個功能:
(1) 通過ExecuteNonQuery.方法執(zhí)行SQL語句:
///<summary>
/// 執(zhí)行ExecuteNonQuery
///</summary>
privatevoid ExecuteNonQuery_Click(object sender, EventArgs e)
{
db.ExecuteNonQuery(CommandType.Text, "INSERT INTO [College] ([CollegeID],[Name]) values (6,'體育學(xué)院')");
}
(2) 執(zhí)行ExecuteDataSet,返回DataSet類型的數(shù)據(jù)集.
///<summary>
/// 執(zhí)行ExecuteDataSet,返回College列表
///</summary>
///<returns></returns>
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) 執(zhí)行ExecuteScalar,返回第一行第一列的值.
///<summary>
/// 執(zhí)行ExecuteScalar,返回第一行第一列的值
///</summary>
///<returns></returns>
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 ="獲取的學(xué)院名稱為:"+ (string)db.ExecuteScalar(dc);
MessageBox.Show(str);
sql ="select [CollegeID] from College where [CollegeID] = 1";
dc = db.GetSqlStringCommand(sql);
str ="獲取的學(xué)院ID為:"+ (int)db.ExecuteScalar(dc);
MessageBox.Show(str);
}
(4) 執(zhí)行存儲過程.
///<summary>
/// 執(zhí)行存儲過程
///</summary>
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) 通過代碼實現(xiàn)事務(wù).
///<summary>
/// 事務(wù)
///</summary>
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, "文旅學(xué)院");
DbCommand dc2 = db.GetStoredProcCommand("usp_College_Insert");
db.AddInParameter(dc2, "@CollegeID", DbType.Int32, 7);
db.AddInParameter(dc2, "@Name", DbType.String, "化工學(xué)院");
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
//添加一個ID為7的學(xué)院
db.ExecuteNonQuery(dc1, trans);
//添加一個ID為7的學(xué)院,主鍵重復(fù),事務(wù)將回滾
db.ExecuteNonQuery(dc2, trans);
//提交事務(wù).
trans.Commit();
}
catch
{
//回滾
trans.Rollback();
}
conn.Close();
}
//查看數(shù)據(jù)庫,數(shù)據(jù)未被添加,說明事務(wù)已回滾
ExecuteDataSet_Click(null, null);
}
(6) 通過DataSet更新數(shù)據(jù)庫.
///<summary>
/// 通過DataSet更新數(shù)據(jù)庫
///</summary>
privatevoid DataSetUpdate_Click(object sender, EventArgs e)
{
DataSet productsDataSet =new DataSet();
string sql ="Select * From College";
DbCommand cmd = db.GetSqlStringCommand(sql);
string CollegeTableName ="College";
//恢復(fù)原始數(shù)據(jù)
db.LoadDataSet(cmd, productsDataSet, CollegeTableName);
//獲取數(shù)據(jù)表格
DataTable dTable = productsDataSet.Tables[CollegeTableName];
//添加一個新信息入DataSet中
DataRow addedRow = dTable.Rows.Add(newobject[] { 8, "外國語學(xué)院" });
//修改一個原有數(shù)據(jù)
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更新數(shù)據(jù)庫
int rowsAffected = db.UpdateDataSet(productsDataSet, CollegeTableName, insertCommand, updateCommand, deleteCommand,
Microsoft.Practices.EnterpriseLibrary.Data.UpdateBehavior.Standard);
MessageBox.Show("影響的行數(shù):"+ rowsAffected);
}
(7) 返回值XML化.
///<summary>
/// 返回值XML化
///</summary>
privatevoid ReturnXML_Click(object sender, EventArgs e)
{
//使用"FOR XML AUTO"參數(shù)使得SQL返回XML格式的信息
SqlDatabase sqldb = (SqlDatabase)DatabaseFactory.CreateDatabase("ConnectionString");
DbCommand cmd = sqldb.GetSqlStringCommand("SELECT * FROM College FOR XML AUTO");
IEnumerable<string> 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) 將返回的數(shù)據(jù)對象化.
///<summary>
/// DataAsObject
///</summary>
privatevoid DataAsObject_Click(object sender, EventArgs e)
{
//將返回的數(shù)據(jù)對象化
var results = db.ExecuteSprocAccessor<College>("usp_College_LoadAll");
MessageBox.Show(results.ElementAt(0).ToString());
}
(9) 異步訪問數(shù)據(jù)庫.
///<summary>
/// 異步訪問數(shù)據(jù)庫
///</summary>
privatevoid Async_Click(object sender, EventArgs e)
{
//創(chuàng)建新的數(shù)據(jù)庫連接,屬性必須添加: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());
}
}
//當(dāng)獲取完畢執(zhí)行該函數(shù)
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());
}
}