2014-09-28 40 views
-1

我希望創建一個使用TADOQuery的函數,並且我可以傳遞一個select語句,它將依次從數據庫中提取結果並將結果作爲TList返回從TADOQuery返回一個TList

function GetList(SelectStatement : string) : TList; 
var 
    ResultList : TList; 
Begin 
    with ADOQuery do 
    Begin 
     close; 
     SQL.Clear; 
     SQL.Add(SelectStatement); 
     open; 
     //This is where am not sure 
     //Get the results and populate the ResultList 
    End; 

    Result := ResultList; 
End; 

請注意,該函數是一個泛型,所以不能「硬編碼」ResultList。

以上是可以實現的嗎?

+1

從TList是指針的集合,這將是您預期的結果或什麼是你的意圖? – bummi 2014-09-28 07:04:01

+0

至少您應該在列表中告訴我們您想要的字段。 – 2014-09-28 07:05:00

+0

@Jens Borrisholt - 該函數應該是一個通用的,使得返回的字段取決於提供的Select語句。 – KE50 2014-09-28 07:12:11

回答

3

您可能會使用一個變體數組來存儲一行的字段和這些「行數組」的通用列表來保留這些數組。

uses Generics.Collections; 
{$R *.dfm} 

Type 
    TVarArray = Array of Variant; 
    TVarList = TList<TVarArray>; 

Function GetAds2List(Ads:TAdoDataset):TVarList; 

    Function GetRow:TVarArray; 
    var 
    i: Integer; 
    begin 
     SetLength(Result, ADS.FieldCount); 
     for i := 0 to ADS.FieldCount - 1 do 
     begin 
     Result[i] := ADS.Fields[i].Value; 
     end;  
    end; 
begin 
    Result := TVarList.Create; 
    Ads.First; 
    While not ADS.Eof do 
    begin 
     Result.Add(GetRow); 
     Ads.Next; 
    end; 
end; 

用法示例:

procedure TForm3.Button1Click(Sender: TObject); 
var 
    l:TVarList; 
    I,J: Integer; 
    s:String; 
    Function sep(idx:Integer):String; 
    begin 
    if idx=0 then 
     Result := '' 
    else 
     Result := ' , ';  
    end; 
begin 
    ReportMemoryLeaksOnShutDown := true; 
    l := GetAds2List(Ads1); 
    for I := 0 to l.Count - 1 do 
     begin 
     s := ''; 
     for j := 0 to High(l[i]) do 
      begin 
      s := s + sep(j) + VarToStrDef(l[i][j],'*NULL*'); 
      end; 
     memo1.lines.add(s); 
     end;  
    l.Free; 
end;