Frage

My Delphi application using PostgreSQL database (with UniDac components). Data are stored in UTF8 in database. To read international characters, I use this handler:

procedure TdmMain.OnGetText(Sender: TField; var Text: String;
  DisplayText: Boolean);
begin
  Text := Utf8decode (Sender.AsString);
end;

But, how possible to store data, back to DB? I created another handler, OnSetText, with Sender.AsString := Utf8Encode (Text); but it is not working.

How it is possible to do that? Thanks.

War es hilfreich?

Lösung

When reading and editing data, you don't need to recode utf-8 text by yourself (for example, in the OnGetText event). It is enough to set the UseUnicode option in the TUniConnection.SpecificOptions property to True, for example, as follows:

UniConnection1.SpecificOptions.Values['PostgreSQL.UseUnicode'] := 'True';

and UniDAC will do this automatically.

http://www.devart.com/unidac/docs/pgsqlprov_article.htm

Andere Tipps

Although this questions is old, and I agree that translation should occur automatically, sometimes it simply does not work. My workaround is to define a TStringField descendant, in a package:

unit MyField;
.
.
.
Type 

TMyStringField = class(TStringField)
  protected
    procedure SetAsString(const Value: string); override;
    Function GetAsString : String; Override;
  end;

  function TMyStringField.GetAsString: String;
  begin
    Result := inherited Utf8ToAnsi (GetAsString)
  end;

  procedure TMyStringField.SetAsString(const Value: string);
  begin
    inherited SetAsString(AnsiToUtf8(Value))
  end;

Don't forget to register this field:

Procedure Register;
begin
  RegisterFields([TMyStringField]);
end;

From help:

Call RegisterFields to allow custom descendants of TField to appear in the field type drop down of the new field dialog box.

The FieldClasses parameter is an array of TField descendants.In C++, the FieldClasses_Size is the index of the last class in the array (one less than the number of class types).

This approach has the disadvantage that you must add the fields by hand, or replace TStringField to TMyStringField

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top