TSQLQuery.FieldByName (). AsString & # 8594; TStringStream Corrupts Data

I am using Delphi XE2. My code retrieves data from a SQL-Server 2008 R2 database. The returned data is an nvarchar(max) field with 1,055,227 bytes of data. I use the following code to save 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 check the file in hexadecimal view, the first 524,287 bytes (exactly 1/2 megabytes) look correct. The remaining bytes (524,288 to 1,055,227) are all zeros (# 0) instead of the original data.

Is this the right way to save a string field from TSQLQuery to a file? I decided to use TStringStream because in the end I will add code to do other things for the data in the stream that I cannot do with TFileStream .

+4
source share
1 answer

TStringStream TEncoding -aware in XE2, but you do not specify any encoding in the constructor, so TEncoding.Default will be used, which means that any string you provide to it will be internally converted to OS by default Ansi encoding. Make sure the encoding supports the Unicode characters you are trying to work with, or specify a more suitable encoding, for example TEncoding.UTF8 .

Also, make sure that AsString returns the correct and correct UnicodeString value to begin with. TStringStream will not save data correctly if garbage is specified as input. Make sure FieldByName() returns a pointer to a TWideStringField object, not a TStringField object, in order to properly process the Unicode data of the database.

+5
source

All Articles