[英]UTF-8 decoding when reading a MySQL column of type JSON (vs. TEXT), using Perl DBI + DBD::mysql
[英]utf-8 string getting truncated in MySQL table using Perl/DBI
我试图使用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')");
它实际上写的是“N”。 (什么时候应该写“纽伯格林”)
查看MySQL查询日志,我看到:
271 Query INSERT INTO testtable (textval) VALUES ('the Nürburgring')
所以字符串完整地到达DB服务器。
如果我直接在MySQL控制台中输入相同的查询:
INSERT INTO testtable (textval) VALUES ('the Nürburgring');
整个字符串都正确写入。 知道我做错了什么吗?
你设置了属性mysql_enable_utf8
,所以你向接口承诺你会给它一个Perl字符串。 但是,这是Latin1编码中八位字节的缓冲区。
use Devel::Peek qw(Dump);
Dump "the N\xfcrburgring";
# FLAGS = (POK,READONLY,pPOK)
# PV = 0x208e4f0 "the N\374rburgring"\0
修复很简单。 要么在没有\\x
转义的情况下记录文字字符,请使用utf8
编译指示告诉Perl您的源代码是UTF-8并使用编辑器以UTF-8编码保存源代码...
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"]
...或将八位字节解码为字符串。 大多数情况下,你处理的不是文字,而是来自外部的数据,所以要更好地了解编码的整个主题 。
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.