mysqlarraysdelphimydac

Delphi: How to load the contents of the table (mysql) into an Array [1..50] of Float?


I have a table in a datasource module using MyDAC. I want to load the contents of the table, column months with 50 rows into an Array [1..50] of Float. How can I do this?

This is the code of my datamodule unit:

unit Unit2;

interface

uses
  System.SysUtils, System.Classes, Data.DB, DBAccess, MyAccess, MemDS;

type
  TDataModule2 = class(TDataModule)
    MyConnection1: TMyConnection;
    MyQuery1: TMyQuery;
    MyQuery1Months: TFloatField;
    MyQuery1Qob: TFloatField;
    MyQuery1Qcalc: TFloatField;
    MyDataSource1: TMyDataSource;
    MyTable1: TMyTable;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  DataModule2: TDataModule2;

implementation

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

end.

Solution

  • It appears that you have a table with 3 columns, each of which is typed Float. (Though I can't help but wonder why a column called "months" would contain floating-point data.) You wouldn't load that data into an array of 50 floats; you'd load it into an array of 50 records or objects containing 3 fields.

    But let's say you only wanted to load the values of one of the fields. That would go something like this:

    i := 1; //index variable into the array
    myQuery1.Open; //run the database query
    while not myQuery1.EOF do //loop until we reach the end of the dataset
    begin
       myArray[i] := MyQuery1Qcalc.value; //read the field value to the array
       myQuery1.Next; //next record
       inc(i); //next array index
    end;
    

    Be aware that if this result set contains a different number of records than the expected 50, you'll have trouble. It might be better to use a dynamic array and set its length equal to the dataset's RecordCount property after calling Open. But that's the basic pattern for loading data: open the dataset, (or call First on it if it's already open,) then read values from the fields and call Next until you reach the EOF (End Of File, which in this case actually means End Of Record Set.)