TSQLQuery.FieldByName()。AsString-> TStringStream损坏数据 [英] TSQLQuery.FieldByName().AsString -> TStringStream Corrupts Data

查看:68
本文介绍了TSQLQuery.FieldByName()。AsString-> TStringStream损坏数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Delphi XE2。我的代码从SQL-Server 2008 R2数据库中提取数据。返回的数据是 nvarchar(max)字段,其中包含1,055,227字节的数据。我使用以下代码将字段数据保存到文件中:

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;

当我在十六进制查看器中检查文件时,前524,287个字节(恰好是1/2兆)看起来很正确。其余字节(524,288到1,055,227)全为空(#0),而不是原始数据。

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.

这是从 TSQLQuery 到文件?我选择使用 TStringStream ,因为最终我将添加代码以对流中的数据执行其他操作,而这对于 TFileStream是无法实现的

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.

推荐答案

TStringStream 是<$在XE2中支持c $ c> TEncoding ,但是您没有在构造函数中指定任何编码,因此将使用 TEncoding.Default ,这意味着您提供给它的任何字符串都将在内部转换为操作系统默认的Ansi编码。确保编码支持您尝试使用的Unicode字符,或者指定更合适的编码,例如 TEncoding.UTF8

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.

还要确保 AsString 返回一个有效且正确的 UnicodeString 值。 TStringStream 如果将数据作为垃圾输入,将无法正确保存数据。确保 FieldByName()返回的指针是 TWideStringField 对象,而不是 TStringField 对象,以便正确处理数据库的Unicode数据。

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.

这篇关于TSQLQuery.FieldByName()。AsString-&gt; TStringStream损坏数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆