Is there any simple way to compare connection strings without parsing it myself?

前端 未结 2 440
死守一世寂寞
死守一世寂寞 2021-02-06 10:30

I need to be able to compare two different connection strings together and identify whether or not they are the same info. I cannot do a simple string comparison, because the pr

2条回答
  •  醉酒成梦
    2021-02-06 11:15

    To get a collection of the ConnectionString properties, you can assign the ConnectionString to TADOConnection (without actually connecting to the DB) and use TADOConnection.Properties collection (collection item is ADOInt.Property_) e.g.:

    ADOConnection.Properties.Get_Item('Data Source')
    

    You should probably compare specific properties to determine if the connection is set to a specific data store via a specific provider. e.g.:
    Provider, Data Source, Initial Catalog, User ID \ Password (optional).

    There are many properties that you might want to ignore depending on the provider e.g:
    Workstation ID, Persist Security Info, Use Procedure for Prepare, Auto Translate, etc...

    Here is an example how to iterate the TADOConnection properties collection:

    var
      ADOConnection: TADOConnection;
      PropName, PropValue: WideString;
      I: Integer;
    
      ADOConnection := TADOConnection.Create(nil);
      try
        ADOConnection.ConnectionString := 'Provider=MSDASQL.1;Password=secret;Data Source=127.0.0.1;User ID=user;Initial Catalog=mycatalog';
        for I := 0 to ADOConnection.Properties.Count - 1 do
        begin
          // Properties.Item[I] is ADOInt.Property_
          PropName := ADOConnection.Properties.Item[I].Name;
          PropValue := VarToWideStr(ADOConnection.Properties.Item[I].Value);
          ShowMessage(Format('%s=%s', [PropName, PropValue]));
        end;
      finally
        ADOConnection.Free;
      end;
    

    There might be much more properties that are added to/changed in the ConnectionString after TADOConnection was connected to the DB, so you need to take this into account.

提交回复
热议问题