ikathegreat
ikathegreat

Reputation: 2331

listing SQL table's rows in text file

I am new in using SQL with Delphi. I have a table, i.e.:

ColumnName1 ColumnName2 ColumnName3
Value 1a    Value2a     Value3a
Value 1b    Value2b     Value3b
Value 1c    Value2c     Value3c

and so on. I have the table displayed on a DBGrid so currently the ADODataSet is all connected ok. However I have a small loop

for I := 0 to ADODataSet.FieldCount - 1 do begin
  WriteLn(WOLFile,ADODataSet.Fields[I].AsString);
end;

That writes to a text file. This text file does not have the column names, and lists the Fields, one per line.

Value 1a
Value 2a
Value 3a
Value 1b
Value 2b
Value 3b

etc. How can I get it to list in a row format, similar to how I've represented the complete table above?

Upvotes: 0

Views: 432

Answers (1)

No'am Newman
No'am Newman

Reputation: 6477

In order to get the fieldnames, you would have to write something like this

   for I := 0 to ADODataSet.FieldCount - 1 do 
    Write (WOLFile,ADODataSet.Fields[I].displayname);
   writeln (WOLFile);

Output the data only with 'write', so that all the column names appear in the same line, then open a new line with 'writeln'.

Then you can add your code which iterates over the table. Here's the entire code:

with ADODataSet do
 begin
  for i:= 0 to fieldcount - 1 do write (WOLFile, Fields[I].displayname);
  writeln (WOLFile);
  first;
  while not eof do
   begin
    for I := 0 to FieldCount - 1 do Write (WOLFile, Fields[I].AsString);
    writeln (WOLFile);
    next
   end;
  end;
 end;

The columns probably won't left align correctly, but I'll leave that little problem up to you.

People here don't like the use of the 'with' construct but I don't see any problem in this snippet.

You could also save the output in a stringlist then write the stringlist to a file at the end, instead of using write and writeln. In order to do that, you would have to concatenate the values of each 'for i' loop into a local variable then add that variable to the stringlist. If you add each value to be printed directly to the stringlist, then every value will appear on a separate line.

Upvotes: 4

Related Questions