人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

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

發(fā)布日期:2021-12-23 08:08 | 文章來源:站長(zhǎng)之家

引言

我一直在尋找一種簡(jiǎn)單有效的庫(kù),它能在簡(jiǎn)化數(shù)據(jù)庫(kù)相關(guān)的編程的同時(shí)提供一種異步的方法來預(yù)防死鎖。

我找到的大部分庫(kù)要么太繁瑣,要么靈活性不足,所以我決定自己寫個(gè)。

使用這個(gè)庫(kù),你可以輕松地連接到任何 SQL-Server 數(shù)據(jù)庫(kù),執(zhí)行任何存儲(chǔ)過程或 T-SQL 查詢,并異步地接收查詢結(jié)果。這個(gè)庫(kù)采用 C# 開發(fā),沒有其他外部依賴。

背景

你可能需要一些事件驅(qū)動(dòng)編程的背景知識(shí),但這不是必需的。

使用

這個(gè)庫(kù)由兩個(gè)類組成:

1、BLL (Business Logic Layer) 提供訪問MS-SQL數(shù)據(jù)庫(kù)、執(zhí)行命令和查詢并將結(jié)果返回給調(diào)用者的方法和屬性。你不能直接調(diào)用這個(gè)類的對(duì)象,它只供其他類繼承.
2、DAL (Data Access Layer) 你需要自己編寫執(zhí)行SQL存儲(chǔ)過程和查詢的函數(shù),并且對(duì)于不同的表你可能需要不同的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類維護(hù)著處理異步查詢的線程,你需要提供必要的數(shù)據(jù)來拼接連接字符串。千萬(wàn)別忘了調(diào)用`Stop`函數(shù),否則析構(gòu)函數(shù)會(huì)強(qiáng)制調(diào)用它。

NOTE:如果需要連接其他非MS-SQL數(shù)據(jù)庫(kù),你可以通過修改BLL類中的`CreateConnectionString`函數(shù)來生成合適的連接字符串。

為了調(diào)用存儲(chǔ)過程,你應(yīng)該在DAL中編寫這種函數(shù):

public int MyStoreProcedure(int param1, string param2) 
{ 
  // 根據(jù)存儲(chǔ)過程的返回類型創(chuàng)建用戶數(shù)據(jù) 
  StoredProcedureCallbackResult userData = new StoredProcedureCallbackResult(eRequestType.Scalar); 
   
  // 在此定義傳入存儲(chǔ)過程的參數(shù),如果沒有參數(shù)可以省略 <span style="line-height:1.5;font-size:9pt;">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ǔ)過程的返回值類型可以是`Scalar`,`Reader`和`NonQuery`。對(duì)于 `Scalar`,`userData`的`ScalarValue`參數(shù)有意義(即返回結(jié)果);對(duì)于`NonQuery`,`userData`的 `AffectedRows`參數(shù)就是受影響的行數(shù);對(duì)于`Reader`類型,`ReturnValue`就是函數(shù)的返回值,另外你可以通過 `userData`的`resultDataReader`參數(shù)訪問recordset。

再看看這個(gè)示例:

public bool MySQLQuery(int param1, string param2) 
{ 
  // Create user data according to return type of store procedure in SQL(這個(gè)注釋沒有更新,說明《注釋是魔鬼》有點(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查詢,但思想跟 `ExecuteStoredProcedure` 是一樣的。

我們使用 `resultDataReader` 的 `.Read()` 方法來迭代處理返回的結(jié)果集。另外提供了一些helper方法來避免疊代中由于NULL字段、GetIntValueOfDBField 等引起的異常。

如果你要執(zhí)行 SQL 命令而不是存儲(chǔ)過程,需要傳入 ExecuteSQLStatement 的 userData 有三類:

1、ReaderQueryCallbackResult userData:適用于有返回recordset的語(yǔ)句,可以通過userData.resultDataReader獲得對(duì)返回的recordset的訪問。
2、NonQueryCallbackResult userData:適用于像UPDATE這種沒有返回內(nèi)容的語(yǔ)句,可以使用userData.AffectedRows檢查執(zhí)行的結(jié)果。
3、ScalarQueryCallbackResult userData:用于查詢語(yǔ)句只返回一個(gè)標(biāo)量值的情況,例如`SELECT code FROM tbl WHEN ID=10`,通過userData.ScalarValue 取得返回的結(jié)果。
對(duì)于存儲(chǔ)過程,只有一種需要傳入 ExecuteStoredProcedure 的數(shù)據(jù)類型。但在聲明變量時(shí)你需要指明存儲(chǔ)過程的返回值類型:

StoredProcedureCallbackResult userData(eRequestType):除了聲明不同外,其他操作與上面相同。
異步地使用代碼

假使你不希望調(diào)用線程被查詢阻塞,你需要周期性地調(diào)用 `WaitSqlCompletes` 來檢查查詢是否完成,執(zhí)行是否失敗。

/// <summary> 
/// 你需要周期性地調(diào)用WaitSqlCompletes(userData, 10) 
/// 來查看結(jié)果是否可用! 
/// </summary> 
public StoredProcedureCallbackResult MyStoreProcedureASYNC(int param1, string param2) 
{ 
  // Create user data according to return type of store procedure in SQL 
  StoredProcedureCallbackResult userData = new StoredProcedureCallbackResult(eRequestType.Reader); 
   
  // If your store procedure accepts some parameters, define them here, 
  // or you can omit it incase there is no parameter definition 
  userData.Parameters = new System.Data.SqlClient.SqlParameter[] { 
    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"); 
     
  return userData; 
} 

在調(diào)用線程中你需要這樣做:

... 
DAL.StoredProcedureCallbackResult userData = myDal.MyStoreProcedureASYNC(10,"hello"); 
... 
// each time we wait 10 milliseconds to see the result... 
switch(myDal.WaitSqlCompletes(userData, 10)) 
{ 
case eWaitForSQLResult.Waiting: 
 goto WAIT_MORE; 
case eWaitForSQLResult.Success: 
 goto GET_THE_RESULT; 
default: 
 goto EXECUTION_FAILED; 
} 
... 

數(shù)據(jù)庫(kù)狀態(tài)

在 BLL 中只有一個(gè)異步地提供數(shù)據(jù)庫(kù)狀態(tài)的事件。如果數(shù)據(jù)庫(kù)連接被斷開了(通常是由于網(wǎng)絡(luò)問題),OnDatabaseStatusChanged 事件就會(huì)被掛起。

另外,如果連接恢復(fù)了,這個(gè)事件會(huì)被再次掛起來通知你新的數(shù)據(jù)庫(kù)狀態(tài)。

有趣的地方

在我開發(fā)代碼的時(shí)候,我明白了連接字符串中的連接時(shí)限(connection timeout)和SQL命令對(duì)象的執(zhí)行時(shí)限(execution timeout)同樣重要。

首先,你必須意識(shí)到最大容許時(shí)限是在連接字符串中定義的,并可以給出一些執(zhí)行指令比連接字符串中的超時(shí)時(shí)間更長(zhǎng)的時(shí)間。

其次,每一個(gè)命令都有著它們自己的執(zhí)行時(shí)限,在這里的代碼中默認(rèn)為30秒。你可以很容易地修改它,使它適用于所有類型的命令,就像這樣:

userData.tsWaitForResult = TimeSpan.FromSeconds(15); 

以上就是異步的SQL數(shù)據(jù)庫(kù)封裝全部過程,希望對(duì)大家的學(xué)習(xí)有所幫助。

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部