ADO连接池

ADO连接池
unit unADOConnectionPool;

interface
uses
  Windows,ADODB;

const
  MAX_CONNECTION_COUNT=5;
type

  TADOConnectionPool=class
  private
//    _CirticalSection:TCriticalSection;
    _ConnectionCount:integer;
    _ADOConnections:array of TADOConnection;
    _Mutexs:array of THandle;
  protected
    function FindConnectionIndex(Connection:TADoconnection):Integer ;
  public
    constructor Create(ConnectionCount:Integer=MAX_CONNECTION_COUNT);
    destructor Destroy; override;
    function InitConnection(ConnectionString:string):Integer;
    function GetConnection():TADoconnection ;
    procedure FreeConnection(Connection:TADoconnection);
  end;


  function GetADOConnectionPool():TADOConnectionPool ;
implementation

var
  ADOConnectionPool:TADOConnectionPool=nil;

function GetADOConnectionPool():TADOConnectionPool ;
begin
  if not Assigned(ADOConnectionPool) then
    ADOConnectionPool:=TADOConnectionPool.Create();
  Result:=ADOConnectionPool;
end;

{ TADOConnectionPool }


constructor TADOConnectionPool.Create(ConnectionCount:Integer);
var
  i:integer;
begin
//  _CirticalSection:=TCriticalSection.Create;
  _ConnectionCount:= ConnectionCount;

  SetLength(_ADOConnections,_ConnectionCount);
  SetLength(_Mutexs,_ConnectionCount);
  for i:=Low(_Mutexs) to High(_Mutexs) do
  begin
    _Mutexs[i]:=CreateMutex(nil,False,'');

  end;
end;

destructor TADOConnectionPool.Destroy;
var
  i:integer;
begin
  for i:=Low(_Mutexs) to High(_Mutexs) do
  begin
    CloseHandle( _Mutexs[i]);
  end;

  for i:=Low(_ADOConnections) to High(_ADOConnections) do
  begin
    _ADOConnections[i].Free;
  end;
//  _CirticalSection.Free;
  inherited;
end;

function TADOConnectionPool.FindConnectionIndex(
  Connection: TADoconnection): Integer;
var
  i:integer;
begin
  Result:=-1;
  for i:=Low(_ADOConnections) to High(_ADOConnections) do
  begin
    if Connection= _ADOConnections[i] then
    begin
      Result:=i;
      break;
    end;
  end;
end;

procedure TADOConnectionPool.FreeConnection(Connection:TADoconnection);
var
  iFindIndex:integer;
begin
  iFindIndex:=FindConnectionIndex(Connection);
  if 0<=iFindIndex then
   ReleaseMutex(_Mutexs[iFindIndex]);
end;

function TADOConnectionPool.GetConnection: TADoconnection;
var
  iConnectionIndex:integer;
begin
  Result:=nil;
//  _CirticalSection.Enter;
  iConnectionIndex:=WaitForMultipleObjects(_ConnectionCount,@_Mutexs[0],False,INFINITE) -WAIT_OBJECT_0 ;
  //OutputDebugString( PChar(Format(' ----%d ',[iConnectionIndex])));
  if iConnectionIndex<_ConnectionCount then
    Result:=_ADOConnections[iConnectionIndex];
//  _CirticalSection.Leave;
end;

function TADOConnectionPool.InitConnection(ConnectionString: string):Integer;
var
  i:integer;
begin
  Result:=0;

  for i:=Low(_ADOConnections) to High(_ADOConnections) do
  begin
    _ADOConnections[i]:=TADOConnection.Create(nil);
    try
      _ADOConnections[i].LoginPrompt:=False;
      _ADOConnections[i].ConnectionString:=ConnectionString;
      _ADOConnections[i].Connected:=True;
    except
      Result:=-1;
    end;
  end;

end;

initialization

finalization
  ADOConnectionPool.Free;
end.


测试中学习到的问题

1、    _Mutexs[i]:=CreateMutex(nil,False,'');
在创建的线程中,无论Mutex 是否在信号状态(也就是 第二个参数是True或) 创建线程调用WaitForMultipleObjects 都会成功

2、当拥有Mutex的线程没有ReleaseMutex就结束了,在WaitForMultipleObjects 的线程将返回WAIT_ABANDONED_0 ,标号是拥有Mutex的标号

Delphi TThread中文注释2009-10-22 16:58TThread是一个抽象类,可以创建几个独立的线程。 类关系 TObject 在一个多线程的应用程序中创建一个TThread的后子类代表一个线程。每一新子类的TThread对象的实例是一个新的线程。从TThread派生的多线程实例可以构成Delphi的多线程应用程序。    当一个应用程序运行时,应用程序就被载入内存准备执行。此时,它成为包含一个或多个线程的进程,每个线程含有数据、代码和系统资源。线程执行应用程序的部分内容,并由系统分配CPU时间。同一进程的所有线程共享同一地址空间,可以访问进程的全局变量。线程通过以下工作改善应用的性能:管理多通信设备的输入。    区分任务的优先级。优先级高的处理紧急的任务。优先级低的处理其他任务。    以下是使用线程的一些建议:    同时跟踪太多的线程消耗CPU时间。对单处理器系统,一个进程最多有16个线程。    当多个线程更新相同的资源时,应使线程同步以避免冲突。    大多数访问VCL对象和更新窗体的方法必须从主VCL线程内部调用。    以下为创建和使用一个新线程的过程:    (1)单击File|New|Thread菜单项,创建一个包含对象的新单元,该对象源于TThread类。    (2)定义新线程对象和Create方法。    (3)通过插入线程执行时需要的代码定义线程对象和Execute方法。    (4)将使用VCL组件的任何调用传递给Synchronize方法,以避免多线程冲突。
一个使用ADO连接池的示例,演示了TADOStoredProc动态参数的使用,带重连机制 =================== unit UnitDemo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm2 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; //数据库服务器 gDBServer: String = '127.0.0.1'; //数据库名称 gDBName: String = 'master'; //数据库用户名 gDBUser: String = 'sa'; //密码 gDBPass: String = '2001'; implementation {$R *.dfm} uses ADODB, UnitADOConnectionPool; const CreateSQL = 'create procedure TestMyPool (@type sysname) '#13#10+ 'as'#13#10+ 'select * from sysobjects where xtype=@type'#13#10+ 'return @@rowcount'; DeleteSQL = 'if Exists(select 1 from sysobjects where xtype=N''P'' and name=N''TestMyPool'')'#13#10+ ' drop procedure TestMyPool'; var gPoolMan: TADOConnPoolMan = Nil; procedure TForm2.Button1Click(Sender: TObject); var ADOObject:TADOConnPoolObject; ADOStoredProc:TADOStoredProc; Running :Integer; I: Integer; begin //取得一个存储过程资源(含一数据库有效连接) ADOObject := gPoolMan.CreateSP('TestMyPool'); if ADOObject = Nil then //取得资源失败 Exit; try ADOStoredProc := ADOObject.ExecObject as TADOStoredProc; Running := 2;//允许重试(两次)操作,以便在操作失败之后达到重连 while Running>0 do begin Dec(Running); if ADOObject.NeedRefresh then begin//判断是否有重连标志(比如数据库断开等,可能需要进行重连) if Not ADOObject.Reconnect then Exit; ADOObject.NeedRefresh := Not ADOStoredProc.Parameters.Refresh; if ADOObject.NeedRefresh then Exit; end; for I := 1(*Zero is the *Result* Parameter*) to ADOStoredProc.Parameters.Count - 1 do begin //========================= //传递参数 ADOStoredProc.Parameters.Items[I].Value := 'U'; //========================= end; if Running 0 then try //执行存储过程 ADOStoredProc.Open; //执行存储过程成功,退出循环进入后续的数据处理 break; except On E:Exception do begin //执行失败非程序级的异常通常有两种可能: //1.数据库连接断开 //2.自适合的参数传递当中可能存储过程已更新,参与不一致 //设置重连标志 ADOObject.NeedRefresh := True; //=================== //这里记录数据库操作失败日志 //=================== end; end; Exit; end; //========================== //从ADOStoredProc当中读取记录 ShowMessage(IntToStr(ADOStoredProc.Parameters.ParamByName('Result').Value)); //========================== //关闭存储对象的资源 ADOStoredProc.Close; finally //调用结束,释放资源 ADOObject.Free; end; end; procedure TForm2.FormCreate(Sender: TObject); var ADOConn:TADOConnection; begin (****************BEGIN*******************) (*注:仅为测试准备 *) //初始化测试环境 ADOConn := Nil; if Not TADOConnPoolMan.ConnectADO( gDBServer,gDBUser,gDBPass,gDBName,true,ADOConn) then Exit; try ADOConn.Execute(DeleteSQL); ADOConn.Execute(CreateSQL); finally try ADOConn.Close; except end; ADOConn.Free; end; (*****************END********************) //初始化连接池 gPoolMan := TADOConnPoolMan.Create(gDBServer,gDBUser,gDBPass,gDBName,true); end; procedure TForm2.FormDestroy(Sender: TObject); var ADOConn:TADOConnection; begin //释放连接池 if Assigned(gPoolMan) then gPoolMan.Free; (****************BEGIN*******************) (*注:仅为测试准备 *) //清理测试环境 ADOConn := Nil; if Not TADOConnPoolMan.ConnectADO( gDBServer,gDBUser,gDBPass,gDBName,true,ADOConn) then Exit; try ADOConn.Execute(DeleteSQL); finally try ADOConn.Close; except end; ADOConn.Free; end; (*****************END********************) end; end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值