我正在尝试使用perl/DBI将utf-8字符串写入MySQL表。由于某些原因,字符串在第一个非ascii字符处被截断。
例如,如果我设置下表:
CREATE DATABASE testdb DEFAULT CHARSET=utf8;
CREATE TABLE testdb.testtable (textval CHAR(30)) DEFAULT CHARSET=utf8;
然后运行以下perl代码:
#!/usr/bin/perl
use strict;
use DBI;
my $dbh = DBI->connect('DBI:mysql:host=localhost;database=testdb', 'testuser', 'somepassword', {mysql_enable_utf8 => 1}) or die $DBI::errstr;
$dbh->do('SET NAMES utf8');
$dbh->do("INSERT INTO testtable (textval) VALUES ('the N\xFCrburgring')");
它实际上写的是"the N“。(当它应该写“纽伯格林”时)
查看MySQL查询日志,我看到以下内容:
271 Query INSERT INTO testtable (textval) VALUES ('the Nürburgring')
因此,字符串将原封不动地到达DB服务器。
如果我直接在MySQL控制台中输入相同的查询:
INSERT INTO testtable (textval) VALUES ('the Nürburgring');
整个字符串都被正确写入。知道我做错了什么吗?
发布于 2011-10-29 18:40:04
您设置了属性mysql_enable_utf8
,因此您向接口承诺将为其提供一个Perl字符串。但是,这是Latin1编码中的八位字节缓冲区。
use Devel::Peek qw(Dump);
Dump "the N\xfcrburgring";
# FLAGS = (POK,READONLY,pPOK)
# PV = 0x208e4f0 "the N\374rburgring"\0
修复方法很简单。使用utf8
编译指示符来告诉\x
您的源代码是UTF8格式的,并使用编辑器…以UTF8编码保存源代码
use utf8;
use Devel::Peek qw(Dump);
Dump "the Nürburgring";
# FLAGS = (POK,READONLY,pPOK,UTF8)
# PV = 0x20999f0 "the N\303\274rburgring"\0 [UTF8 "the N\x{fc}rburgring"]
…或者将八位字节解码为字符串。大多数时候,你要处理的不是文字,而是来自外部的数据,所以最好使用learn about the whole topic of encoding。
use Encode qw(decode);
use Devel::Peek qw(Dump);
Dump decode 'Latin1', "the N\xfcrburgring";
# FLAGS = (TEMP,POK,pPOK,UTF8)
# PV = 0x208f6b0 "the N\303\274rburgring"\0 [UTF8 "the N\x{fc}rburgring"]
https://stackoverflow.com/questions/7935934
复制相似问题