Delphi TQuery 的Locate用法

Help里的解释数据库

function Locate(const KeyFields: String; const KeyValues: Variant; Options: TLocateOptions): Boolean;函数

KeyFields: is a string containing a semicolon-delimited list of field names on which to search.code

KeyValues: is a variant array containing the values to match in the key fields.

TLocateOptions is a set that optionally specifies additional search latitude when searching on string fields.

关于LocateOptions
type
  TLocateOption = (loCaseInsensitive, loPartialKey);
  TLocateOptions = setof TLocateOption;

loCaseInsensitive Key fields and key values are matched without regard to case.//忽略大小写
loPartialKey Key values can include only part of the matching key field value; //只需部分匹配,从头开始匹配 
{另外,若是KeyFields里没有字符串类型或者LocateOptions=[],该函数都会忽略此项}

看了这么多,到底Locate是干么的呢?请看

Searches the dataset for a specified record and makes that record the current record.ci

Call Locate to search a dataset for a specific record and position the cursor on it.

很显然Locate有别于过虑,可不要等同起来哦。Locate主要是在已经Open出来的数据集里定位你要的资料。

好了,看了Help里面密密麻麻的E文,头都晕了,是否是由于头晕因此一直学很差“英国历史(English)”呢?我怎么看E文都是这种感受,仍是中国的方块字看起来亲切舒服,^_^,扯远了,言归正传,看了理论的东西,咱们来实践一下。

作事情老是从易处着手,写程序也不例外。咱们先看看单栏的用法。

strCode:='Abc'
Tquery1.Locate('code',strcode,[loCaseInsensitive])

这样TQuery,就会将光标定位到code字段中等于Abc(abc,aBc,abC,....)的记录上。

不过,咱们既然用来查询大部分状况下咱们都是要模糊查询的,因此这样并非咱们要用的方法,咱们只要稍微改下Option就OK了。
Tquery1.Locate('code',strcode,[loPartialKey])

这样找到的是这样的结果code中“包含”(是从头开始匹配而不是真正的包含)Abc(Abcddfe...,....)

固然也能够两个同时使用

字符串

Tquery1.Locate('code',strcode,[loCaseInsensitive,loPartialKey])string

 

with CustTable do
  Locate('Company;Contact;Phone', VarArrayOf(['Sight Diver', 'P', '408-431-1000']), [loPartialKey]);it

  一、使用“;”来分割多个字段名称,用VarArrayOf()来传递多个定位值。
  二、字段必定要和数据库彻底同样,即便你用习惯了的空格也不行。虽然使得程序看起来跟清楚点,可是Locate不会本身作Trim,因此它把空格也当成字段名称的一部分。
  三、由于定位值采用Variants,因此定位就不知局限于字符串了。
  四、对于多栏查询的结果,必定要全部栏位所有符和才能够,只要有一栏不符合,就会返回False。
  5.  最好不用对空值进行定位,会进行从头至尾的遍历,影响速度.io

 Ok,关于Locate的用法就说到这里,写个小例子看成总结。function

 var
  LocateSuccess: Boolean;
  SearchOptions: TLocateOptions;
  StrField,StrLocate:String;//字段名称,定位值
begin
  SearchOptions := [loCasesensitive,loPartialKey];
  LocateSuccess := CustTable.Locate(StrField,StrLocate, SearchOptions);
end;遍历

相关文章
相关标签/搜索