TSQLQuery.FieldByName().AsString -> TStringStream Corrupts Data

丶灬走出姿态 提交于 2019-12-10 05:53:06

问题


I'm using Delphi XE2. My code pulls data from a SQL-Server 2008 R2 database. The data returned is a nvarchar(max) field with 1,055,227 bytes of data. I use the following code to save the field data to a file:

procedure WriteFieldToFile(FieldName: string; Query: TSQLQuery);
var
  ss: TStringStream;
begin
  ss := TStringStream.Create;
  try
    ss.WriteString(Query.FieldByName(FieldName).AsString);
    ss.Position := 0;
    ss.SaveToFile('C:\Test.txt');
  finally
    FreeAndNil(ss);
  end;
end;

When I inspect the file in a hex viewer, the first 524,287 bytes (exactly 1/2 meg) look correct. The remaining bytes (524,288 to 1,055,227) are all nulls (#0), instead of the original data.

Is this the right way to save a string field from a TSQLQuery to a file? I chose to use TStringStream because I will eventually add code to do other things to the data on the stream, which I can't do with a TFileStream.


回答1:


TStringStream is TEncoding-aware in XE2, but you are not specifying any encoding in the constructor so TEncoding.Default will be used, meaning that any string you provide to it will internally be converted to the OS default Ansi encoding. Make sure that encoding supports the Unicode characters you are trying to work with, or else specify a more suitable encoding, such as TEncoding.UTF8.

Also make sure that AsString is returning a valid and correct UnicodeString value to begin with. TStringStream will not save the data correctly if it is given garbage as input. Make sure that FieldByName() is returning a pointer to a TWideStringField object and not a TStringField object in order to handle the database's Unicode data correctly.



来源:https://stackoverflow.com/questions/12210174/tsqlquery-fieldbyname-asstring-tstringstream-corrupts-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!