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;遍歷

相關文章
相關標籤/搜索