?
Solved

Help With ADOQuery.Locate

Posted on 2011-02-23
13
Medium Priority
?
1,909 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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:Ephraim Wangoya
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 38

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 38

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
 
LVL 32

Expert Comment

by:Ephraim Wangoya
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:Ephraim Wangoya
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 38

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:
Ephraim Wangoya earned 1000 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses
Course of the Month14 days, 18 hours left to enroll

770 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