天天看點

如何在.NET應用程式中使用資料庫層

大多數應用軟體的開發都是在一個多層或者多級的環境中完成的,除非你是在用過時的代碼或系統在工作。這可能包括了與業務規則和表示層一起的資料庫層。每一個n層環境的關鍵部分就是資料庫層。在這篇專欄文章裡,我們将分析怎樣在.NET 的應用程式中使用資料庫層。

代碼分離

無論你是在建構一個網站、Windows作業系統、網站服務,還是其他任何一種應用程式,你肯定要将資料庫的CRUD(建立、讀取、更新和删除)操作合并。許多開發者經常從像網頁這樣的應用資源裡直接調用資料庫,但是這樣就會導緻噩夢般的維護或代碼變換——尤其是當有必要改變資料庫通路的時候。

目前的一種産業趨勢是将資料通路代碼同其餘的代碼相分離。用這種方式,你可以通過資料通路代碼進行所需的資料庫調用。這樣就使得你能夠在不涉及應用程式其餘部分的情況下,進行資料庫通路或者改變代碼。除此之外,你還可以完全将資料通路代碼移至它自己所屬的類,在應用程式中重複使用它。

和其他為應用程式開發所做的努力一樣,有不止一種的方法來處理它。你可以采取某種政策,使資料通路代碼資料庫變得獨立,這樣就會使得在不影響其他應用程式層的情況下,打開後端資料庫變得很容易。另外,你的環境中還可以有一個标準化的後端資料庫,是以就可能不需要那麼高的透明級别了。

而且,你可以選擇讓資料通路代碼通用化,以便讓其适用于多個應用程式,或者為某個特定程式量身定制資料通路代碼。和大多數話題一樣,應用程式開發者會争論某種方法要比另一種方法好,但是到最後,它還是取決于你的環境、項目和時間限制。讓我們來探讨一下在.NET 應用程式中資料通路層的運用。

建構資料通路層

基本上來說,資料通路層隻是我們寫入的與資料源互相作用的代碼;它可以很簡單,也可以很複雜,這根據你的需要來決定。舉個例子,我們将建立一個資料通路類來處理與曾經風靡一時的SQL Server Northwind資料庫之間的互相操作。我們的應用程式需要執行以下的資料庫操作:

  • 向使用者表添加新的使用者
  • 從使用者表删除使用者
  • 檢視使用者表中包括的使用者資訊
  • 在Northwind資料庫中運作存儲過程。

我們從建立資料通路類開始。前面清單中的每個項目所對應的方法都包括在内。該類包含了以下方法來處理這些函數:

  • GetDataSet方法接受一個單獨的,包含了要運作的存儲程式名稱的字元串參數。程式執行後,結果儲存在一個DataSet對象中,該對象又通過此方法被傳回。
  • GetCustomers方法是GetDataSet方法的一個變體,但是它是為了和Northwind的使用者表互相作用專門定制的,然後在一個DataSet對象中傳回所有的列。
  • AddCustomer方法接受需要的資料并向資料庫添加記錄。
  • DeleteCustomer方法把記錄辨別作為整數接受,它被用來從資料庫中删除适當的記錄。
  • RunProcedure方法接受一個字元串值,其中包括了在後端資料庫運作的存儲程式的名稱。
  • GetDataReader方法接受一個字元串變量中的存儲程式名稱。這個程式在後端資料庫中運作,其結果由該方法作為一個SqlDataReader對象被傳回。
  • WriteToEventLog方法被所有方法用來記錄Windows事件日志中的所有異常。

資料庫連接配接字元串被儲存在Web.config檔案中(這在Web的應用程式被使用),但是app.config檔案也可以被使用。類的ConnectionString屬性從配置檔案中檢索得到值。而且,所有的方法都是靜态的,是以它們可以不需要經過類的執行個體例示就可以使用。檢視清單A。

清單A

using System;

using System.Configuration;

using System.Data;

using System.Diagnostics;

using System.Data.SqlClient;

public class DataAccess {

static String connectionString;

public static String ConnectionString {

get {

if (connectionString == null) {

try {

connectionString = (String) ConfigurationSettings.AppSettings["connStr"];

} catch {

throw new Exception("Connection string not set in web.config.");

}

if (connectionString == null) {

throw new Exception("Connection string not set in web.config.");

} }

return connectionString;

} }

public static DataSet GetDataSet(string ProcName) {

DataSet tempDS = null;

SqlConnection conn = null;

SqlDataAdapter sda = null;

try {

tempDS = new DataSet();

conn = new SqlConnection(ConnectionString);

conn.Open();

sda = new SqlDataAdapter(ProcName, conn);

sda.Fill(tempDS);

return tempDS;

} catch (Exception ex) finally }

public static DataSet GetCustomers() {

DataSet tempDS = null;

SqlConnection conn = null;

SqlDataAdapter sda = null;

try {

tempDS = new DataSet();

conn = new SqlConnection(ConnectionString);

conn.Open();

sda = new SqlDataAdapter("sp_GetCustomers", conn);

sda.Fill(tempDS);

return tempDS;

} catch (Exception ex) finally }

public static void AddCustomer( string pCompanyName, string pContactName, string pContactTitle, string pAddress, string pCity, string pState, string pPostalCode, string pCountry, string pPhone, string pFax) {

SqlConnection conn = null;

SqlCommand comm = null;

SqlParameter param1 = null;

SqlParameter param2 = null;

SqlParameter param3 = null;

SqlParameter param4 = null;

SqlParameter param5 = null;

SqlParameter param6 = null;

SqlParameter param7 = null;

SqlParameter param8 = null;

SqlParameter param9 = null;

SqlParameter param10 = null;

string procName = "sp_Add_Customer";

try {

conn = new SqlConnection(ConnectionString);

conn.Open();

comm = new SqlCommand(procName, conn);

comm.CommandType = CommandType.StoredProcedure;

param1 = new SqlParameter("@CompanyName", SqlDbType.NVarChar, 40);

param1.Value = pCompanyName;

comm.Parameters.Add(param1);

param2 = new SqlParameter("@ContactName", SqlDbType.NVarChar, 30);

param2.Value = pContactName;

comm.Parameters.Add(param2);

param3 = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30);

param3.Value = pContactTitle;

comm.Parameters.Add(param3);

param4 = new SqlParameter("@Address", SqlDbType.NVarChar, 60);

param4.Value = pAddress;

comm.Parameters.Add(param4);

param5 = new SqlParameter("@City", SqlDbType.NVarChar, 15);

param5.Value = pCity;

comm.Parameters.Add(param5);

param6 = new SqlParameter("@State", SqlDbType.NVarChar, 40);

param6.Value = pState;

comm.Parameters.Add(param6);

param7 = new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10);

param7.Value = pPostalCode;

comm.Parameters.Add(param7);

param8 = new SqlParameter("@Country", SqlDbType.NVarChar, 15);

param8.Value = pCountry;

comm.Parameters.Add(param8);

param9 = new SqlParameter("@Phone", SqlDbType.NVarChar, 24);

param9.Value = pPhone;

comm.Parameters.Add(param9);

param10 = new SqlParameter("@Fax", SqlDbType.NVarChar, 24);

param10.Value = pFax;

comm.Parameters.Add(param10);

comm.ExecuteNonQuery();

} catch (Exception ex) finally }

public static void DeleteCustomer(string pCustomerID) {

SqlConnection conn = null;

SqlCommand comm = null;

SqlParameter param = null;

string procName = "sp_Delete_Customer";

try {

conn = new SqlConnection(ConnectionString);

conn.Open();

comm = new SqlCommand(procName, conn);

comm.CommandType = CommandType.StoredProcedure;

param = new SqlParameter("@CustomerID", SqlDbType.NVarChar, 5);

param.Value = pCustomerID;

comm.Parameters.Add(param);

comm.ExecuteNonQuery();

} catch (Exception ex) finally }

public static void RunProcedure(string pProcedureName) {

SqlConnection conn = null;

SqlCommand comm = null;

try {

conn = new SqlConnection(ConnectionString);

comm =new SqlCommand(pProcedureName, conn);

conn.Open();

comm.ExecuteNonQuery();

} catch(Exception ex) finally }

public static SqlDataReaderGetDataReader(string pProcedureName) {

SqlConnection conn = null;

SqlCommand comm = null;

SqlDataReadersdr = null;

try {

conn = new SqlConnection(ConnectionString);

comm = new SqlCommand(pProcedureName, conn);

conn.Open();

sdr = comm.ExecuteReader(CommandBehavior.CloseConnection);

} catch(Exception ex)

return sdr;

}

private static void WriteToEventLog(Exception objError) {

EventLogobjEventLog = new EventLog();

objEventLog.Source = "TechRepublic.com Application";

objEventLog.WriteEntry(objError.Message.ToString());

} }

當這個類準備就緒之後,你可以很容易地在應用程式中使用它。例如,一個DataGrid可以利用DataAccess和資料庫互動作用。它可以利用由GetCustomers傳回的DataSet對象。同樣地,其他的方法也可以用來對後端資料進行操作。