3

我正在尝试使用 DBD::Pg 将 UTF8 字符串插入 PostgreSQL,并且总是在数据库中获得双编码的 UTF8。如果我插入的字符串是 Latin1,我只会在数据库中得到正确的字符。

如何告诉 DBD::Pg 不要重新编码已经是 UTF8 的字符串?

测试脚本:

!/usr/bin/perl

use strict;

my $PGDB      = 'dbi:Pg:dbname=test;host=localhost';
my $PGDB_USER = 'username';    
my $SQL_INSERT = 'INSERT INTO tmp1 (t1, t2) VALUES (?, ?)';

use DBI;

my $dbh = DBI->connect($PGDB, $PGDB_USER)
    || die "Couldn't connect to $PGDB as user $PGDB_USER: $DBI::errstr\n";

#$dbh->do("SET client_encoding TO UTF8");

my $sth = $dbh->prepare( $SQL_INSERT )
    || die "Can't prepare insert statement $SQL_INSERT: $DBI::errstr";

my $cp1252 = "\xe9 voil\xe0";
my $utf8   = "é voilà";

utf8::upgrade($utf8);

use utf8;
#use bytes;

my $text = 'sent utf8 w. utf8::upgrade';

$sth->execute($utf8, $text) or die $sth->errstr, "\n";

经过几次测试后的结果表:

é voilà     sent cp1252 as_is w. use bytes
é voilà   sent utf8 as_is w. use bytes
é voilà   sent utf8 as_is w. use utf8
é voilà     sent cp1252 as_is w. use utf8
é voilà     sent cp1252 as_is w. do(SET client_encoding TO UTF8)
é voilà   sent utf8 as_is w. do(SET client_encoding TO UTF8)
é voilà   sent utf8 as_is w. use utf8 + do(SET client_encoding TO UTF8)
é voilà   sent utf8 w. utf8::upgrade + do(SET client_encoding TO UTF8)
é voilà   sent utf8 w. utf8::upgrade

(这是在带有 DBD::Pg 版本 3.5.3 的 Ubuntu 16.04 上。安装在 Ubuntu 12.04 上的 DBD::Pg 版本没有这个问题)

4

0 回答 0