0

As the title suggests, using Delphi 2010 and MyDAC 7.1, how do I output an entire string as a string like JSON / XML / CSV or some other plain text option?

eg output:

{user_id:1;username:testuser;password:testpass}
SupaMonkey
  • 876
  • 2
  • 9
  • 25

2 Answers2

1

According to the documentation you can use the SaveToXML procedures. should be something like this:

var
  MyQuery: TMyQuery;

begin

  try
    MyQuery := TMyQuery.Create();
    MyQuery.Connection := AConnection;
    MyQuery.SQL.Text := ACommand;

    MyQuery.Execute();
    MyQuery.SaveToXML(<tstream or file>)

  except
    raise;
  end;
end;
Miguel Febres
  • 2,153
  • 2
  • 21
  • 31
1

Presuming that MyDAC is a standard TDataSet descendant, you can build the string manually. For instance, for JSON:

var
  i: Integer;
  Output: string;
begin
  Output := '{';                                        // #123;
  for i := 0 to MyQry.FieldCount - 1 do
    Output := Output + 
              MyQry.Fields[i].FieldName + ':' +         // #58
              MyQry.Fields[i].AsString + ';';           // #59
  // Replace final ; with closing } instead
  Output[Length(Output)] := '}';                        // #125
end;

Or you can Google to find a Delphi JSON library (like SuperObject) and use it instead, as is done here.

For XML, use the same type loop with TXMLDocument. You can search for previous posts here tagged with Delphi to find examples.

For CSV, it can get complicated based on your data and the requirements. For instance, do you want or need a header row with field names? Does your data contain data that contains spaces or punctuation or CR/LFs? The easiest solution is to search for an already-existing library (via Google or Bing, not here) that exports to CSV.

Community
  • 1
  • 1
Ken White
  • 123,280
  • 14
  • 225
  • 444