tags:

views:

930

answers:

2

Hello

Since Embarcadero's NNTP server stopped responding since yesterday, I figured I could ask here: I work with a non-DB-aware grid, and I need to loop through a dataset to extract the number of columns, their name, the number of rows and the value of each fields in each row.

I know to read the values for all the fields in each row, but I don't know how to extract column-related information. Does someone have some code handy?

procedure TForm1.FormCreate(Sender: TObject);
var
  index : Integer;
begin
  With ASQLite3DB1 do begin
      DefaultDir := ExtractFileDir(Application.ExeName);
      Database := 'test.sqlite';
      CharacterEncoding := 'STANDARD';
      Open;
  end;

  With ASQLite3Query1 do begin
    ASQLite3Query1.Connection := ASQLite3DB1;

    SQL.Text := 'CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, label VARCHAR)';
    ExecSQL;

    SQL.Text := 'INSERT INTO mytable (label) VALUES ("dummy label")';
    ExecSQL;

    SQL.Text := 'SELECT id AS Identification, label AS Label FROM mytable';
    Open;

    //How to get column numbers + names to initialized grid object?
    for index := 0 to ASQLite3Query1. - 1 do begin

    end;

    for index := 0 to FieldCount - 1 do begin
      ShowMessage(Fields[index].AsString);
    end;
  end;
end;

Thank you.

+1  A: 

Number of fields and their names could be acquired as follows:

procedure TForm1.Button1Click(Sender: TObject);
begin
  with Query1 do
  begin
 ShowMessage(IntToStr(FieldCount));
 ShowMessage(Fields[0].FieldName);
  end;
end;

You can checkout TFieldDef for more detail info about the field.

dataset.FieldDefs[0] has properties like DataType and Size.

eed3si9n
+1  A: 

If what you're looking for is a list of field names, try creating a TStringList and passing it to the TDataset.Fields.GetFieldNames procedure.

If you want more information about fields, the TFields object (ASQLite3Query1.Fields) has a default property and a Count property, so you can use it like an array, and an enumerator, both of which can be used to loop over each TField object and retrieve its metadata.

Mason Wheeler
Mason, I did edit the question by improving the code formatting, I didn't change the "handy?.", but I saw your name with code formatting revision which I did and mine with "handy?", seems it's concurrency problem with SO :-)
Mohammed Nasman
Not sure what you mean. I fixed the code formatting, and didn't touch anything else in the post, the first time. Later on, after I noticed the ?. thing, I fixed that too, but that was long afterwards.
Mason Wheeler
I mean, I didn't made the changes in revision marked with my name, I did the same code regarding the code formatting (removed [code] tags), but I saw it marked with your name, so I thought it was concurrency problem with SO.
Mohammed Nasman
Thanks everyone.
OverTheRainbow