delphiadodelphi-xe2

How to Check Delphi TADOConnection.State


I have a method which performs some operations on a TADOConnection object, which sometimes seems to occur when the connection is in a state which would not permit this operation. When this happens, an exception is thrown and processing fails. I want to enclose the method in an if statement which simply checks the state of the TADOConnection to ensure it is closed before proceeding.

Therefore, I have the following:

procedure MyClass.OperateOnADOConnection;
begin
  if ADOConnection.State = stClosed then
  begin
    //do my operations
  end;
end;

I get a compile time error for this, because State and stClosed are apparently not the same object type. I also tried if ADOConnection.State = TObjectStates.stClosed then but then I got a different error.

Delphi documentation is pretty limited and doesn't really explain how things are used, as far as I can see. I do not have access to a Delphi IDE as I am not usually a Delphi programmer and licenses are limited - so I am using Visual Studio Code. No online tutorials that I have found make mention of the .State property, either.

How am I supposed to use this property?


Solution

  • The State property is defined as a Set of TObjectState values:

    A set is a collection of values of the same ordinal type. The values have no inherent order, nor is it meaningful for a value to be included twice in a set.

    The State can hold multiple TObjectState values at one time. You are trying to compare the entire Set to a specific value, which is why you are getting errors. You should instead be checking if the desired value is contained within the Set. You can use the in operator for that purpose, eg:

    //if ADOConnection.State = stClosed then
    if stClosed in ADOConnection.State then