Solved

Help With ADOQuery.Locate

Posted on 2011-02-23
13
1,636 Views
Last Modified: 2012-05-11
I am trying to create a function that does nothing be a locate on an ADOQuery based on fields and values passed in. This is the code I was trying to use.

Function PositionTable(Var MyDataTable : TADOQuery;{**************************}
                       Const MyKeyFieldStr : String;{List of Fields Seperated by ;}
                       const MyKeyValues : Array of String) : Boolean;
Begin
  PositionTable := MyDataTable.Locate(MyKeyFieldStr, VarArrayOf(MyKeyValues), [loCaseInsensitive]);
End;

This however does not work it gives me an error with the locate stement. Can Some one Please help me to get code that will allow the function to do the adoquery.locate How it works does not concern me however the eaiser the setup of the variables to pass to the function the better.
0
Comment
Question by:malachi223
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 19

Expert Comment

by:Thommy
ID: 34960942
You should call TAdoQuery.locate like this:

MyDataTable.Locate('Name;Town;Country', VarArrayOf(['Miller', 'Los Angeles', 'America']), [loPartialKey]);
0
 
LVL 19

Expert Comment

by:Thommy
ID: 34960949
Please provide error...
0
 
LVL 32

Expert Comment

by:ewangoya
ID: 34961111
Create a variant array on the fly
Function PositionTable(Var MyDataTable : TADOQuery;{**************************}
                       Const MyKeyFieldStr : String;{List of Fields Seperated by ;}
                       const MyKeyValues : Array of String) : Boolean;
var
  I, Len: Integer;
  SearchValues: Variant;
Begin
  Len := Length(MyKeyValues);
  SearchValues := VarArrayCreate([0, Len-1], varVariant);
  for I := 0 to Len -1 do
    SearchValues[I] := MyKeyValues[I];
  PositionTable := MyDataTable.Locate(MyKeyFieldStr, SearchValues, [loCaseInsensitive]);
End;

Open in new window

0
 
LVL 36

Expert Comment

by:Geert Gruwez
ID: 34962002
there is no need to use var in your function !
actually you must not use it

Function PositionTable(MyDataTable : TADOQuery;
                       Const MyKeyFieldStr : String;{List of Fields Seperated by ;}
                       const MyKeyValues : Array of String) : Boolean;
0
 
LVL 1

Author Comment

by:malachi223
ID: 34965210
Below is my new Code as Suggested and I get an error. Could Not Convert Variant of type(Array Varriant) Into type (String).

Function PositionTable(MyDataTable : TADOQuery;{**************************}
                       Const MyKeyFieldStr : String;{List of Fields Seperated by ;}
                       const MyKeyValues : Array of String) : Boolean;
Var SearchValues : Variant;
    Idx : Integer;
    Len : Integer;
Begin
  Len := Length(MyKeyValues);
  SearchValues := VarArrayCreate([0, Len-1], varVariant);
  for Idx := 0 to Len -1 do
    SearchValues[Idx] := MyKeyValues[Idx];
  PositionTable := MyDataTable.Locate(MyKeyFieldStr, SearchValues, [loCaseInsensitive]);
End;
0
 
LVL 36

Expert Comment

by:Geert Gruwez
ID: 34965446
new to delphi ?
why not use TDataset ?
you could then use this as a more generic function

what version  of delphi do you have ?

function PositionTable(MyDataTable : TDataset;
                       const MyKeyFieldStr : String;
                       const MyKeyValues : array of string) : Boolean;
var SearchValues : Variant;
Begin
  DynArrayToVariant(SearchValues, @MykeyValues, TypeInfo(string));
  Result := MyDataTable.Locate(MyKeyFieldStr, SearchValues, [loCaseInsensitive]);
End;
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 32

Expert Comment

by:ewangoya
ID: 34966348

I just tested the code and it works, unless you are not passing in the correct data to the procedure
0
 
LVL 1

Author Comment

by:malachi223
ID: 34969750
I am useing Delphi 7 I am not new to dephi though this stupid function sure is making me feel like I am. Something so common and I cant get it :-(
When I use the DynArrayToVariant function it blows up with the following error.
Invalid Variant Type Conversion. Here is the code.

Function PositionTable(MyDataTable : TADOQuery;{**************************}
                       Const MyKeyFieldStr : String;{List of Fields Seperated by ;}
                       Const MyKeyValues : Array of String) : Boolean;
Var SearchValues : Variant;
Begin
  DynArrayToVariant(SearchValues, @MykeyValues, TypeInfo(String));
  PositionTable := MyDataTable.Locate(MyKeyFieldStr, SearchValues, [loCaseInsensitive]);
End;

As far as what I am passing into the routine this is one of the spots the code that calls the routine and blows up. Note the quotes around the SearchChar in the call to PositionTable. There is a field in the table called SearChar.

Procedure CheckRec(ReplacementTable : TADOQuery);
Var     SearchChar : String;
begin
   SetLength(IndexFieldArray,1);
   IndexFieldArray[0] := SearchChar;
   If PositionTable(ReplacementTable, 'SearchChar', IndexFieldArray) Then
    Begin
    End
end;
0
 
LVL 32

Expert Comment

by:ewangoya
ID: 34969919

There is no value assigned to SearchChar, basically your are sending an empty string to be searched. I suppose this is why you are getting errors

Are you trying to pass in a value to this procedure?



procedure CheckRec(ReplacementTable : TADOQuery; const ASearchText: string); overload
begin
   //SetLength(IndexFieldArray,1); //no need for this if you are searching one item
   //IndexFieldArray[0] := SearchChar; 
   If PositionTable(ReplacementTable, 'SearchChar', [ASearchText]) Then
   Begin
   End
end;

//you would call it like
CheckRec(Query1, 'George');

Open in new window

0
 
LVL 36

Expert Comment

by:Geert Gruwez
ID: 34979252
you are not new to delphi ?

why not just use locate directly ?
i don't see any point in writing a secondary wrapper function for that

Procedure CheckRec(ReplacementTable : TADOQuery; SearchText: string);
begin
  If ReplacementTable.Locate('SearchColumns', SearchText, [loCaseInsensitive]) then  
  begin
    ShowMessage('By golly, miss molly, you found a record !');  
  end;
end;
0
 
LVL 1

Author Comment

by:malachi223
ID: 34979721
Sorry I was missing the line of code that sets the SearchChar it gets set from a table. As for just doing the locate directly it is because the fields and vales of what I am searching for differ depending on the contents of a table. The code I have posted is obviously not my code in its entirety. just the parts that are pertant to the problem. Ewangoya what version of delphi are you useing. Can you also post the exact code you have that works for you becasue so far it is not working for me. Also as a side notenot that it should matter but these routines are in a seperate unit no on the form where the table resides that I am locateing the data. Finally what are you includeing in your uses for this all to work. There must be something different from what I have and what you have if yours works and mine does not.
0
 
LVL 32

Accepted Solution

by:
ewangoya earned 250 total points
ID: 34989322
Here is code to do the search as you want
I created an object for that
There is also a small test based on northwind database
unit Unit3;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DB, ADODB, Grids, DBGrids, StdCtrls;

type
  TForm3 = class(TForm)
    ADOConnection1: TADOConnection;
    ADOQuery1: TADOQuery;
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

uses
  uDBSearch;

procedure ValidateSearch(const AKeyFields: string; ASearchData: Variant);
var
  List: TStringList;
  ErrMsg: string;
begin
  ErrMsg := '';
  if Trim(AKeyFields) = '' then
     ErrMsg := 'No Key Fields specified'
  else if VarIsNull(ASearchData) then
     ErrMsg := 'Search data not specified'
  else
  begin
    if Pos(';', AKeyFields) <= 0 then
    begin
      if VarIsArray(ASearchData) then
        ErrMsg := 'Search data and key fields do not match';
    end
    else
    begin
      if not VarIsArray(ASearchData) then
        ErrMsg := 'Search data and key fields do not match'
      else
      begin
        List := TStringList.Create;
        try
          List.Delimiter := ';';
          List.DelimitedText := AKeyFields;
          if VarArrayHighBound(ASearchData, 1) <> List.Count -1 then
            ErrMsg := 'Search data and key fields do not match'
        finally
          FreeAndNil(List);
        end;
      end;
    end;
  end;

  if ErrMsg <> '' then
    raise Exception.Create(ErrMsg);
end;

procedure TForm3.Button1Click(Sender: TObject);
begin
  if TDBSearch.LocateData(ADOQuery1, 'EmployeeID;LastName;FirstName',
      ['1', 'Davolio', 'Nancy'], [loCaseInsensitive], @ValidateSearch) then
   ShowMessage('Good')
  else
   ShowMessage('Bad');
end;

procedure TForm3.FormCreate(Sender: TObject);
begin
  ADOConnection1.Connected := True;
  ADOQuery1.Open;
end;

end.

Open in new window

unit uDBSearch;

interface

uses
  SysUtils, Classes, Variants, DB;

type
  PSearchValidate = ^TSearchValidate;
  TSearchValidate = procedure(const AKeyFields: string; ASearchData: Variant);

  TDBSearch = class(TObject)
  public
    class function LocateData(ADataset: TDataset; const AKeyFields: string;
      ASearchData: array of string; AOptions: TLocateOptions = [];
      PValidate: Pointer = nil): Boolean; overload;
    class function LocateData(ADataset: TDataset; const AKeyFields: string;
      ASearchData: Variant; AOptions: TLocateOptions = [];
      PValidate: Pointer = nil): Boolean; overload;
  end;

implementation

{ TDBSearch }

class function TDBSearch.LocateData(ADataset: TDataset;
  const AKeyFields: string; ASearchData: array of string;
  AOptions: TLocateOptions; PValidate: Pointer): Boolean;
var
  I, Len: Integer;
  SearchValues: Variant;
begin
  Len := Length(ASearchData);
  if Len = 1 then
    SearchValues := ASearchData[0]
  else
  begin
    SearchValues := VarArrayCreate([0, Len-1], varVariant);
    for I := 0 to Len -1 do
      SearchValues[I] := ASearchData[I];
  end;

  Result := LocateData(ADataset, AKeyFields, SearchValues, AOptions, PValidate);
end;

class function TDBSearch.LocateData(ADataset: TDataset;
  const AKeyFields: string; ASearchData: Variant; AOptions: TLocateOptions;
  PValidate: Pointer): Boolean;
begin
  if Assigned(PValidate) then
     TSearchValidate(PValidate)(AKeyFields, ASearchData);

  Result := ADataset.Locate(AKeyFields, ASearchData, AOptions);
end;

end.

Open in new window

0
 
LVL 1

Author Comment

by:malachi223
ID: 34997425
Thanks this code seems to work when I compiled your sample I will double check that it fits with what I am doing and then Accept your solution. Thanks again
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now