简体   繁体   English

在使用MyDAC的Delphi中,如何将整个记录写为字符串?

[英]In Delphi using MyDAC, how do I write an entire record as a string?

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? 如标题所示,如何使用Delphi 2010和MyDAC 7.1将整个字符串输出为JSON / XML / CSV或其他纯文本选项之类的字符串?

eg output: 例如输出:

{user_id:1;username:testuser;password:testpass}

According to the documentation you can use the SaveToXML procedures. 根据文档,您可以使用SaveToXML过程。 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;

Presuming that MyDAC is a standard TDataSet descendant, you can build the string manually. 假定MyDAC是标准的TDataSet后代,则可以手动构建字符串。 For instance, for JSON: 例如,对于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 . 或者,您可以通过Google找到一个Delphi JSON库(例如SuperObject )并使用它,如此处所示

For XML, use the same type loop with TXMLDocument. 对于XML,请对TXMLDocument使用相同的类型循环。 You can search for previous posts here tagged with Delphi to find examples. 您可以在此处搜索以前用Delphi标记的帖子,以查找示例。

For CSV, it can get complicated based on your data and the requirements. 对于CSV,根据您的数据和要求,它可能会变得复杂。 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? 您的数据是否包含包含空格或标点符号或CR / LF的数据? The easiest solution is to search for an already-existing library (via Google or Bing, not here) that exports to CSV. 最简单的解决方案是搜索导出到CSV的现有库(通过Google或Bing,不在此处)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM