Monday, 27 August 2012

How to use TADOQuery in Delphi XE2?

Following is the code snippet which will show you how to use ADOQuery in Delphi XE2?

function TClass1.UseADOQuery : integer;
begin
  try
    with qryADOQuery do
    begin
      Connection := ADOConnection; //Connection name
      Close;
      SQL.Clear;
      SQL.Text :=
        'SELECT ColumnX FROM TableA WHERE ' +
        'ColumnA = :ParameterA AND ' +
        'ColumnB = :ParameterB AND ' +
        'ColumnC = :ParameterC';

      Parameters.ParamByName('ColumnA').Value := ParameterA;
      Parameters.ParamByName('ColumnB').Value := ParameterB;
      Parameters.ParamByName('ColumnC').Value := ParameterC;
      Open;
      if (Recordcount = 0) then
        result := 0
      else
        result := Fields.FieldByName('ColumnX').Value; //Assume ColumnX value is an integer
      Close;
    end;
  except
    on E : Exception do
    begin
      result := 0;
      ShowMessage('Error occured in function UseADOQuery: ' + E.Message);
      exit;
    end;
  end;
end;

Explanation:First of all query has be be initialized with connection name. Now close it if already opened. For being on safer side, we should close it first before using it. Clear the SQL statement if any then write new SQL statement. Parameters to the query are passed by using colon (:) keyword. Recordcount keyword returns the number of rows affected.

No comments:

Post a Comment