Delphi ZeosLib と Delphi 7 を使用して Unicode を SQL Server データベースに挿入し、挿入された値を読み取るのに問題があります。最初に挿入し、次に挿入された値をクエリする簡単なテスト プログラムを作成しました。
テスト テーブル スキーマ:
CREATE TABLE [dbo].[incominglog](
[message] [nvarchar](500) NULL
) ON [PRIMARY]
簡単なテスト プログラム ソース (ZeosLib ソースを含む) をアップロードしました。ここをクリックしてダウンロードしてください。ntwdblib.dll も含めましたが、独自のものを使用できます。
テスト プログラムには、ここからダウンロードできる TNT コンポーネントも必要です。
テスト プログラムを使用すると、挿入した Unicode 文字が検索時に疑問符として表示されます。問題が挿入コードにあるのかクエリ コードにあるのかはわかりません。
また、挿入する前にデータを utf-8 にエンコードし、utf-8 から取得した後にデータをデコードしようとしました。テスト プログラム ソースで「//inserted as utf8」を検索してください。デコード後に Unicode を表示できるので、この方法は機能します。ただし、実際のアプリケーションでは、SQL Server が UTF-8 を完全にサポートしていないため、UTF-8 としてエンコードできません。一部の文字は格納できません。以前の質問はこちらをご覧ください。
ポインタをいただければ幸いです。:)
一方、テストプログラムのソースは次のとおりです。
unit Unit1;
interface
uses
ZConnection, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ZAbstractRODataset, ZAbstractDataset, ZAbstractTable, ZDataset,
StdCtrls, TntStdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
TntMemo1: TTntMemo;
Button2: TButton;
TntEdit1: TTntEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
FZConnection: TZConnection;
FZQuery: TZQuery;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
tntmemo1.Lines.Clear;
FZConnection := TZConnection.Create(Owner);
FZConnection.LoginPrompt := False;
FZQuery := TZQuery.Create(Owner);
FZQuery.Connection := FZConnection;
FZConnection.Protocol := 'mssql';
FZConnection.Database := 'replace-with-your-db';
FZConnection.HostName := 'localhost';
FZConnection.User := 'sa';
FZConnection.Password := 'replace-with-your-password';
FZConnection.Connect;
FZQuery.SQL.Text := 'SELECT * from incominglog';
FZQuery.ExecSQL;
FZQuery.Open;
FZQuery.First;
while not FZQuery.EOF do
begin
tntmemo1.Lines.add(FZQuery.FieldByName('message').AsString);
// tntmemo1.Lines.add(utf8decode(FZQuery.FieldByName('message').AsString)); //inserted as utf8
FZQuery.Next;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
sqlstring, data:widestring;
begin
FZConnection := TZConnection.Create(Owner);
FZConnection.LoginPrompt := False;
FZQuery := TZQuery.Create(Owner);
FZQuery.Connection := FZConnection;
FZConnection.Protocol := 'mssql';
FZConnection.Database := 'replace-with-your-db';
FZConnection.HostName := 'localhost';
FZConnection.User := 'sa';
FZConnection.Password := 'replace-with-your-password';
FZConnection.Connect;
data:= tntedit1.Text;
// data:= utf8encode(tntedit1.Text); //inserted as utf8
sqlstring:= 'INSERT INTO INCOMINGLOG ([MESSAGE]) VALUES(N''' + data + ''')';
FZQuery.SQL.Text := sqlstring;
FZQuery.ExecSQL;
end;
end.