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

字號:


    引言
    我一直在尋找一種簡單有效的庫,它能在簡化數(shù)據(jù)庫相關(guān)的編程的同時提供一種異步的方法來預(yù)防死鎖。
    我找到的大部分庫要么太繁瑣,要么靈活性不足,所以我決定自己寫個。
    使用這個庫,你可以輕松地連接到任何 SQL-Server 數(shù)據(jù)庫,執(zhí)行任何存儲過程或 T-SQL 查詢,并異步地接收查詢結(jié)果。這個庫采用 C# 開發(fā),沒有其他外部依賴。
    背景
    你可能需要一些事件驅(qū)動編程的背景知識,但這不是必需的。
    使用
    這個庫由兩個類組成:
    BLL (Business Logic Layer) 提供訪問MS-SQL數(shù)據(jù)庫、執(zhí)行命令和查詢并將結(jié)果返回給調(diào)用者的方法和屬性。你不能直接調(diào)用這個類的對象,它只供其他類繼承.
    DAL (Data Access Layer) 你需要自己編寫執(zhí)行SQL存儲過程和查詢的函數(shù),并且對于不同的表你可能需要不同的DAL類。
    首先,你需要像這樣創(chuàng)建 DAL 類:
    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類維護著處理異步查詢的線程,你需要提供必要的數(shù)據(jù)來拼接連接字符串。千萬別忘了調(diào)用`Stop`函數(shù),否則析構(gòu)函數(shù)會強制調(diào)用它。
    NOTE:如果需要連接其他非MS-SQL數(shù)據(jù)庫,你可以通過修改BLL類中的`CreateConnectionString`函數(shù)來生成合適的連接字符串。
    為了調(diào)用存儲過程,你應(yīng)該在DAL中編寫這種函數(shù):
    public int MyStoreProcedure(int param1, string param2)
    {
    // 根據(jù)存儲過程的返回類型創(chuàng)建用戶數(shù)據(jù)
    StoredProcedureCallbackResult userData = new StoredProcedureCallbackResult(eRequestType.Scalar);
    // 在此定義傳入存儲過程的參數(shù),如果沒有參數(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í)行完成...
    // 等待時長為 <userdata.tswaitforresult>
    // 執(zhí)行未完成返回 <timeout>
    if (WaitSqlCompletes(userData) != eWaitForSQLResult.Success)
    throw new Exception("Execution failed");
    // Get the result...
    return userData.ScalarValue;
    }
    正如你所看到的,存儲過程的返回值類型可以是`Scalar`,`Reader`和`NonQuery`。對于 `Scalar`,`userData`的`ScalarValue`參數(shù)有意義(即返回結(jié)果);對于`NonQuery`,`userData`的 `AffectedRows`參數(shù)就是受影響的行數(shù);對于`Reader`類型,`ReturnValue`就是函數(shù)的返回值,另外你可以通過 `userData`的`resultDataReader`參數(shù)訪問recordset。
    再看看這個示例:
    public bool MySQLQuery(int param1, string param2)
    {
    // Create user data according to return type of store procedure in SQL(這個注釋沒有更新,說明《注釋是魔鬼》有點道理)
    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;
    }
    在這個例子中,我們調(diào)用 `ExecuteSQLStatement` 直接執(zhí)行了一個SQL查詢,但思想跟 `ExecuteStoredProcedure` 是一樣的。
    我們使用 `resultDataReader` 的 `.Read()` 方法來迭代處理返回的結(jié)果集。另外提供了一些helper方法來避免疊代中由于NULL字段、GetIntValueOfDBField 等引起的異常。