Show quoted text 10 lines
> When you open the query you object is deleted.
> If yuo need only a field name is
>
> Query1.sql.text:= "select * from mytable";
> Query1.open;
> Name:=Query1.Fields[0].fieldname;
>
Thanks for your response, but it does not work.
It works if you don't define your fields yourself.
Show quoted text 11 lines
The table I use has more than five fields. I manually created
one field
(double clicking the sqlQuery and adding one field).
When I run the program, I display Query1.FieldCount : 1.
When I try to display Query1.Fields[1].fieldname ([1], i.e.
the second
fieldname) I get an "list index out of bounds" error.
Displaying Query1.Fields[0].fieldname gives the fieldname of
the field I
manually created.
If you define one field manually at run-time you have only one field. Opening the dataset won't add the fields automatically once you defined your own. I haven't seen this mentioned in fpc/lazarus docs but in Delphi articles on adding fields at run-time it is stated quite clear: if you want to add fe. a calculated field at run-time to the existing dataset fkData fields, you have to define all these fields before adding the new one. If you have fielddefs for the query you can add the existing fields simply with:
for i:=0 to MyQuery.FieldDefs.Count-1 do
Field:=MyQuery.FieldDefs[i].CreateField(MyQuery);
If you don't have fielddefs (0 items) and you don' want to add them in the designer then just add a
SQLQuery1.Active:=true;
SQLQuery1.Active:=false;
before the above loop to auto fill the fielddefs. For this to work, as for fields, Fielddefs should be an empty array. As soon on element is in fielddefs, the auto fill won't work.
Now, in your previous mail you created the field with
Show quoted text 5 lines
tmpField:=TStringField.Create(nil);
tmpField.FieldKind:=fkData;
tmpField.FieldName:='COUNT';
MyQuery.Fields.Add(tmpField);
MyQuery.Open;
This is wrong and fpc 2.7.1 gives even a run-time error saying that dataset is not set. Replace MyQuery.Fields.Add(tmpField); with tmpField.Dataset:=MyQuery;.
Ludo