侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

异步的SQL数据库封装详解

数据库  /  管理员 发布于 6年前   165

引言

我一直在寻找一种简单有效的库,它能在简化数据库相关的编程的同时提供一种异步的方法来预防死锁。

我找到的大部分库要么太繁琐,要么灵活性不足,所以我决定自己写个。

使用这个库,你可以轻松地连接到任何 SQL-Server 数据库,执行任何存储过程或 T-SQL 查询,并异步地接收查询结果。这个库采用 C# 开发,没有其他外部依赖。

背景

你可能需要一些事件驱动编程的背景知识,但这不是必需的。

使用

这个库由两个类组成:

1、BLL (Business Logic Layer) 提供访问MS-SQL数据库、执行命令和查询并将结果返回给调用者的方法和属性。你不能直接调用这个类的对象,它只供其他类继承.
2、DAL (Data Access Layer) 你需要自己编写执行SQL存储过程和查询的函数,并且对于不同的表你可能需要不同的DAL类。
首先,你需要像这样创建 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类维护着处理异步查询的线程,你需要提供必要的数据来拼接连接字符串。千万别忘了调用`Stop`函数,否则析构函数会强制调用它。

NOTE:如果需要连接其他非MS-SQL数据库,你可以通过修改BLL类中的`CreateConnectionString`函数来生成合适的连接字符串。

为了调用存储过程,你应该在DAL中编写这种函数:

public int MyStoreProcedure(int param1, string param2) {   // 根据存储过程的返回类型创建用户数据   StoredProcedureCallbackResult userData = new StoredProcedureCallbackResult(eRequestType.Scalar);      // 在此定义传入存储过程的参数,如果没有参数可以省略 <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");        // 等待执行完成...   // 等待时长为 <userdata.tswaitforresult>   // 执行未完成返回 <timeout>   if (WaitSqlCompletes(userData) != eWaitForSQLResult.Success)     throw new Exception("Execution failed");        // Get the result...   return userData.ScalarValue; } 

正如你所看到的,存储过程的返回值类型可以是`Scalar`,`Reader`和`NonQuery`。对于 `Scalar`,`userData`的`ScalarValue`参数有意义(即返回结果);对于`NonQuery`,`userData`的 `AffectedRows`参数就是受影响的行数;对于`Reader`类型,`ReturnValue`就是函数的返回值,另外你可以通过 `userData`的`resultDataReader`参数访问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 '%{1}%'", 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; } 

在这个例子中,我们调用 `ExecuteSQLStatement` 直接执行了一个SQL查询,但思想跟 `ExecuteStoredProcedure` 是一样的。

我们使用 `resultDataReader` 的 `.Read()` 方法来迭代处理返回的结果集。另外提供了一些helper方法来避免叠代中由于NULL字段、GetIntValueOfDBField 等引起的异常。

如果你要执行 SQL 命令而不是存储过程,需要传入 ExecuteSQLStatement 的 userData 有三类:

1、ReaderQueryCallbackResult userData:适用于有返回recordset的语句,可以通过userData.resultDataReader获得对返回的recordset的访问。
2、NonQueryCallbackResult userData:适用于像UPDATE这种没有返回内容的语句,可以使用userData.AffectedRows检查执行的结果。
3、ScalarQueryCallbackResult userData:用于查询语句只返回一个标量值的情况,例如`SELECT code FROM tbl WHEN ID=10`,通过userData.ScalarValue 取得返回的结果。
对于存储过程,只有一种需要传入 ExecuteStoredProcedure 的数据类型。但在声明变量时你需要指明存储过程的返回值类型:

StoredProcedureCallbackResult userData(eRequestType):除了声明不同外,其他操作与上面相同。
异步地使用代码

假使你不希望调用线程被查询阻塞,你需要周期性地调用 `WaitSqlCompletes` 来检查查询是否完成,执行是否失败。

/// <summary> /// 你需要周期性地调用WaitSqlCompletes(userData, 10) /// 来查看结果是否可用! /// </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; } 

在调用线程中你需要这样做:

... 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; } ... 

数据库状态

在 BLL 中只有一个异步地提供数据库状态的事件。如果数据库连接被断开了(通常是由于网络问题),OnDatabaseStatusChanged 事件就会被挂起。

另外,如果连接恢复了,这个事件会被再次挂起来通知你新的数据库状态。

有趣的地方

在我开发代码的时候,我明白了连接字符串中的连接时限(connection timeout)和SQL命令对象的执行时限(execution timeout)同样重要。

首先,你必须意识到最大容许时限是在连接字符串中定义的,并可以给出一些执行指令比连接字符串中的超时时间更长的时间。

其次,每一个命令都有着它们自己的执行时限,在这里的代码中默认为30秒。你可以很容易地修改它,使它适用于所有类型的命令,就像这样:

userData.tsWaitForResult = TimeSpan.FromSeconds(15); 

以上就是异步的SQL数据库封装全部过程,希望对大家的学习有所帮助。


  • 上一条:
    SQL Server查询数据库中表使用空间信息实现脚本
    下一条:
    数据库访问性能优化
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客