異步的 SQL 數(shù)據(jù)庫(kù)封裝(1)

字號(hào):


    引言
    我一直在尋找一種簡(jiǎn)單有效的庫(kù),它能在簡(jiǎn)化數(shù)據(jù)庫(kù)相關(guān)的編程的同時(shí)提供一種異步的方法來(lái)預(yù)防死鎖。
    我找到的大部分庫(kù)要么太繁瑣,要么靈活性不足,所以我決定自己寫(xiě)個(gè)。
    使用這個(gè)庫(kù),你可以輕松地連接到任何 SQL-Server 數(shù)據(jù)庫(kù),執(zhí)行任何存儲(chǔ)過(guò)程或 T-SQL 查詢(xún),并異步地接收查詢(xún)結(jié)果。這個(gè)庫(kù)采用 C# 開(kāi)發(fā),沒(méi)有其他外部依賴(lài)。
    背景
    你可能需要一些事件驅(qū)動(dòng)編程的背景知識(shí),但這不是必需的。
    使用
    這個(gè)庫(kù)由兩個(gè)類(lèi)組成:
    BLL (Business Logic Layer) 提供訪問(wèn)MS-SQL數(shù)據(jù)庫(kù)、執(zhí)行命令和查詢(xún)并將結(jié)果返回給調(diào)用者的方法和屬性。你不能直接調(diào)用這個(gè)類(lèi)的對(duì)象,它只供其他類(lèi)繼承.
    DAL (Data Access Layer) 你需要自己編寫(xiě)執(zhí)行SQL存儲(chǔ)過(guò)程和查詢(xún)的函數(shù),并且對(duì)于不同的表你可能需要不同的DAL類(lèi)。
    首先,你需要像這樣創(chuàng)建 DAL 類(lèi):
    namespace SQLWrapper
    {
    public class DAL : BLL
    {
    public DAL(string server, string db, string user, string pass)
    {
    base.Start(server, db, user, pass);
    }
    ~DAL()
    {
    base.Stop(eStopType.ForceStopAll);
    }
    ///////////////////////////////////////////////////////////
    // TODO: Here you can add your code here...
    }
    }
    由于BLL類(lèi)維護(hù)著處理異步查詢(xún)的線程,你需要提供必要的數(shù)據(jù)來(lái)拼接連接字符串。千萬(wàn)別忘了調(diào)用`Stop`函數(shù),否則析構(gòu)函數(shù)會(huì)強(qiáng)制調(diào)用它。
    NOTE:如果需要連接其他非MS-SQL數(shù)據(jù)庫(kù),你可以通過(guò)修改BLL類(lèi)中的`CreateConnectionString`函數(shù)來(lái)生成合適的連接字符串。
    為了調(diào)用存儲(chǔ)過(guò)程,你應(yīng)該在DAL中編寫(xiě)這種函數(shù):
    public int MyStoreProcedure(int param1, string param2)
    {
    // 根據(jù)存儲(chǔ)過(guò)程的返回類(lèi)型創(chuàng)建用戶(hù)數(shù)據(jù)
    StoredProcedureCallbackResult userData = new StoredProcedureCallbackResult(eRequestType.Scalar);
    // 在此定義傳入存儲(chǔ)過(guò)程的參數(shù),如果沒(méi)有參數(shù)可以省略 <span>userData.Parameters = new System.Data.SqlClient.SqlParameter[] { </span>
    new System.Data.SqlClient.SqlParameter("@param1", param1),
    new System.Data.SqlClient.SqlParameter("@param2", param2),
    };
    // Execute procedure...
    if (!ExecuteStoredProcedure("usp_MyStoreProcedure", userData))
    throw new Exception("Execution failed");
    // 等待執(zhí)行完成...
    // 等待時(shí)長(zhǎng)為 <userdata.tswaitforresult>
    // 執(zhí)行未完成返回 <timeout>
    if (WaitSqlCompletes(userData) != eWaitForSQLResult.Success)
    throw new Exception("Execution failed");
    // Get the result...
    return userData.ScalarValue;
    }
    正如你所看到的,存儲(chǔ)過(guò)程的返回值類(lèi)型可以是`Scalar`,`Reader`和`NonQuery`。對(duì)于 `Scalar`,`userData`的`ScalarValue`參數(shù)有意義(即返回結(jié)果);對(duì)于`NonQuery`,`userData`的 `AffectedRows`參數(shù)就是受影響的行數(shù);對(duì)于`Reader`類(lèi)型,`ReturnValue`就是函數(shù)的返回值,另外你可以通過(guò) `userData`的`resultDataReader`參數(shù)訪問(wèn)recordset。
    再看看這個(gè)示例:
    public bool MySQLQuery(int param1, string param2)
    {
    // Create user data according to return type of store procedure in SQL(這個(gè)注釋沒(méi)有更新,說(shuō)明《注釋是魔鬼》有點(diǎn)道理)
    ReaderQueryCallbackResult userData = new ReaderQueryCallbackResult();
    string sqlCommand = string.Format("SELECT TOP(1) * FROM tbl1
    WHERE code = {0} AND name LIKE &apos;%{1}%&apos;", param1, param2);
    // Execute procedure...
    if (!ExecuteSQLStatement(sqlCommand, userData))
    return false;
    // Wait until it finishes...
    // Note, it will wait (userData.tsWaitForResult)
    // for the command to be completed otherwise returns <timeout>
    if (WaitSqlCompletes(userData) != eWaitForSQLResult.Success)
    return false;
    // Get the result...
    if(userData.resultDataReader.HasRows && userData.resultDataReader.Read())
    {
    // Do whatever you want....
    int field1 = GetIntValueOfDBField(userData.resultDataReader["Field1"], -1);
    string field2 = GetStringValueOfDBField(userData.resultDataReader["Field2"], null);
    Nullable<datetime> field3 = GetDateValueOfDBField(userData.resultDataReader["Field3"], null);
    float field4 = GetFloatValueOfDBField(userData.resultDataReader["Field4"], 0);
    long field5 = GetLongValueOfDBField(userData.resultDataReader["Field5"], -1);
    }
    userData.resultDataReader.Dispose();
    return true;
    }
    在這個(gè)例子中,我們調(diào)用 `ExecuteSQLStatement` 直接執(zhí)行了一個(gè)SQL查詢(xún),但思想跟 `ExecuteStoredProcedure` 是一樣的。
    我們使用 `resultDataReader` 的 `.Read()` 方法來(lái)迭代處理返回的結(jié)果集。另外提供了一些helper方法來(lái)避免疊代中由于NULL字段、GetIntValueOfDBField 等引起的異常。