Wiliam Cardoso
Wiliam Cardoso

Reputation: 444

How to add items from an SQL query to a TListView

I want to add items from a query into a TListView using a for loop. But I get an error saying 'Too many actual parameters' from the ListViewShifts.Items.Add() line. What is the correct way of adding to the list from a query?

  Qry := TFDQuery.Create(DBConnection);
  Qry.Connection := DBConnection;
  Qry.SQL.Text := 'SELECT Count(10) FROM Bookings WHERE NurseNo=:nurseID;';
  Qry.Params.ParamByName('nurseID').AsInteger := NurseID;
  Qry.Active := True;

  //Fill the list view with the shifts that have the nurses ID
  for Count := 0 to 10 do
  begin
    ListViewShifts.Items.Add(Qry.Fields[Count].AsString);
  end;

Upvotes: 1

Views: 450

Answers (2)

Zhorov
Zhorov

Reputation: 29973

You need to consider the following:

  • If your ListViewShifts variable is TListView, method ListViewShifts.Items.Add doesn't expect parameters. This is the reason for Too many actual parameters error.
  • SQL statement SELECT Count(10) FROM Bookings WHERE NurseNo=:nurseID; will return result set with only one column.
  • If you want to get the first 10 rows, then probably your statement should be: SELECT TOP(10) FROM Bookings WHERE NurseNo=:nurseID;
  • Use First, Eof and Next dataset methods to fetch records from your result set.

Next basic example shows how to add 10 items in your TListView:

procedure TMainForm.btnGet(Sender: TObject);
var
   li: TListItem;
begin

   Qry := TFDQuery.Create(DBConnection);
   Qry.Connection := DBConnection;
   Qry.SQL.Text := 'SELECT TOP(10) FROM Bookings WHERE NurseNo=:nurseID;';
   Qry.Params.ParamByName('nurseID').AsInteger := NurseID;
   Qry.Active := True;

   Qry.First; 
   for Count := 1 to 10 do
   begin
      Qry.Next;
      li := ListViewShifts.Items.Add;
      li.Caption := Qry.Fields[0].AsString;
   end;
   (*
   Qry.First;
   while not Qry.Eof do begin
      li := ListViewShifts.Items.Add;
      li.Caption := Qry.Fields[0].AsString;
      Qry.Next;
   end;
   *)
end;

Upvotes: 3

Güney Uzun
Güney Uzun

Reputation: 21

   VAR
   SY1:INTEGER;
   mydata:string;
   begin
   mydata:='mydatabasename';
   qry_tables.Close;
   qry_tables.SQL.Clear;
   qry_tables.SQL.text:= 'SELECT TABLE_NAME NAME FROM information_schema.TABLES       WHERE TABLE_SCHEMA = '+QuotedStr(mydata);
   qry_tables.Open;

   ListViewShifts.Clear;
   for SY1 := 1 to qry_tables.RecordCount do
    begin
     ListViewShifts.Items.Add(qry_tables.FieldByName('NAME').TEXT);
     qry_tables.NEXT;
    end;

i used mysql

Upvotes: 1

Related Questions