在Perl v5.10.1 中,我尝试读取文件并将字符串存储在数据库中。 当字符串包含重音符号和异域字符时会出现问题。
在我的CentOS 6上,'locale'命令指示: 的 LANG =的en_US.UTF-8
我的数据库是 MySQL ,我写的字段是varchar(64) utf8_unicode_ci 。
我通过Putty控制台运行我的测试,使用Window>设置翻译>远程字符集:UTF8,虽然打印字符是乱码,但这不是主要问题。
这是我的剧本:
#!/usr/bin/perl
use warnings;
use strict;
use utf8;
use open ':std', ':encoding(UTF-8)';
use DBI;
# A test string
my $test = 'é';
print "- 1: $test\n";
# First string in my file, containing a single 'é'
my $string = '';
open(my $fh, '<', 'myFile');
while(my $line = <$fh>) {
chomp $line;
$string = $line;
last;
}
close $fh;
print "- 2: $string\n";
# Writing test string and first string in DB
my $dbistring = 'DBI:mysql:database=xxxx;host=xxxx;port=xxxx';
my $socket = DBI->connect($dbistring, 'xxxx', 'xxxx');
my $cmd = 'UPDATE Strings SET string="'.$test.'" WHERE id=1';
my $request = $socket->prepare($cmd);
$request->execute();
$cmd = 'UPDATE Strings SET string="'.$string.'" WHERE id=2';
$request = $socket->prepare($cmd);
$request->execute();
印刷品如下:
1:▒
2:▒
在我的数据库表格中,字段最终为:
id 1:é
id 2:é
为了避免Perl字符串连接可能出现双重编码,我尝试了:
$string = Encode::decode('UTF-8', $string);
给我相同的结果。 如果我在打开文件时指示'&lt;:encoding(UTF-8)',则相同。
我很困惑,因为我的流程链似乎都是用UTF8设置的。建议非常感谢。
答案 0 :(得分:1)
此valuable article提供了解决方案:
在DBI和DB之间的通信过程中出现问题,并通过在连接期间添加 mysql_enable_utf8 标志来解决:
DBI->connect($dbistring, 'xxxx', 'xxxx', { mysql_enable_utf8 => 1 });
答案 1 :(得分:1)
Perl中的一些问题
use utf8;
use open ':std', ':encoding(UTF-8)';
my $dbh = DBI->connect("dbi:mysql:".$dsn, $user, $password, {
PrintError => 0,
RaiseError => 1,
mysql_enable_utf8 => 1, # Switch to UTF-8 for communication and decode.
});
# or {mysql_enable_utf8mb4 => 1} if using utf8mb4
<强>变为乱码强>
参见&#34; Mojibake&#34;在Trouble with UTF-8 characters; what I see is not what I stored中查看其他问题。