gpt4 book ai didi

Delphi AdoConnection 重新连接

转载 作者:行者123 更新时间:2023-12-03 15:32:09 25 4
gpt4 key购买 nike

我刚刚决定解决 MSSQL 数据库服务器重新启动时的“连接”问题,并且连接永远断开。

到目前为止,唯一的解决方案是重新启动程序,但在距离很远的服务器上并不总是那么容易(并且必须首先检测到问题)。

**下面的代码似乎工作正常,但是熟练的 ADO 人员能否更深入地研究代码并发现此代码是否有任何错误/问题或需要改进? **

Type
TComponentHelper = class helper for TComponent
  Procedure Reconnect(var AdoConn:TAdoConnection; ConnStr:String);
  end;

procedure TComponentHelper.Reconnect(var AdoConn: TAdoConnection; ConnStr: String);
begin
  if Assigned(AdoConn) then begin
    FreeAndNil(AdoConn);
  AdoConn := TAdoConnection.Create(Self);
  AdoConn.ConnectionString := ConnStr;
    AdoConn.LoginPrompt := false;
  SetConnAdoComponent(Self,AdoConn);
  AdoConn.Open;
  end;
end;

procedure SetConnAdoComponent(aSrc:TComponent; var AdoConn:TAdoConnection);
var
Ctrl : TComponent;
i : Integer;
begin
if (aSrc = Nil) then Exit;
if (aSrc.ComponentCount <= 0) then Exit;
for i:=0 to aSrc.ComponentCount-1 do begin
Ctrl := aSrc.Components[i];
if (Ctrl is TAdoQuery) then TAdoQuery(Ctrl).Connection := AdoConn;
if (Ctrl is TAdoTable) then TAdoTable(Ctrl).Connection := AdoConn;
if (Ctrl is TAdoDataset) then TAdoDataset(Ctrl).Connection := AdoConn;
end;
end

我从 TForm 或 TDataModule 中的 Exception 部分调用 Reconnect(),AdoConn 是 TAdoConnection 组件的名称,ConnStr 是使用的完整连接字符串。

Except
On E:EOleException do begin
ReConnect(AdoConn,ConnStr);
end;
On E:Exception do begin
ReConnect(AdoConn,ConnStr);
end;
End;

最佳答案

与其破坏 TADOConnection,最好的选择是用新的替换内部 TADOConnection.ConnectionObject。例如

uses ActiveX, ComObj, ADOInt;

function CreateADOConnectionObject: _Connection;
begin
OleCheck(CoCreateInstance(CLASS_Connection, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER, IUnknown, Result));
end;

var
NewConnectionObject: _Connection;
ConnectionString: WideString;
begin
ConnectionString := ADOConnection1.ConnectionString;
NewConnectionObject := CreateADOConnectionObject;
NewConnectionObject.ConnectionString := ConnectionString;
ADOConnection1.Close;
// set the new connection object
ADOConnection1.ConnectionObject := NewConnectionObject;
ADOConnection1.Open;
end;

设置ADOConnection1.ConnectionObject := NewConnectionObject将销毁之前的内部FConnectionObject并设置一个新的连接对象供TADOConnection对象使用.

此外,您还需要在异常发生时处理特定 EOleException.ErrorCode(可能是E_FAIL),以便确保您不会不处理与您的问题无关的其他异常。

我没有针对您的特定场景(SQL 重新启动)尝试此操作。我将其留给您进行测试。

编辑:使用 SQL Server 2014 和 SQLOLEDB.1 进行测试。我的应用程序连接到 SQL,重新启动 SQL 后,我无法重现所描述的行为“连接永远断开”。 Close/Open 完成了工作,客户端重新连接。

关于Delphi AdoConnection 重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41280679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com