我刚刚决定在重新启动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中的异常部分调用Reconnect(),AdoConn是TAdoConnection组件的名称,ConnStr是使用的完整连接字符串。
Except
On E:EOleException do begin
ReConnect(AdoConn,ConnStr);
end;
On E:Exception do begin
ReConnect(AdoConn,ConnStr);
end;
End;发布于 2016-12-23 07:53:29
您最好的选择不是破坏TADOConnection,而是用一个新的TADOConnection.ConnectionObject替换内部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重新启动)中尝试这一点。我让你来做测试。
编辑:使用Server 2014和SQLOLEDB.1测试。我的应用程序连接到SQL,在重新启动SQL之后,我无法再现所描述的行为“连接永久删除”。Close/Open完成了工作,并且客户端重新连接。
https://stackoverflow.com/questions/41280679
复制相似问题