gpt4 book ai didi

mysql - 使用 Perl/DBI 在 MySQL 表中截断 utf-8 字符串

转载 作者:可可西里 更新时间:2023-11-01 07:06:34 27 4
gpt4 key购买 nike

我正在尝试使用 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”。 (当它应该写“the Nürburgring”时)

查看 MySQL 查询日志,我看到了这个:

271 Query INSERT INTO testtable (textval) VALUES ('the Nürburgring')

因此字符串完整地到达了数据库服务器。

如果我直接在 MySQL 控制台中输入相同的查询:

INSERT INTO testtable (textval) VALUES ('the Nürburgring');

整个字符串都写对了。知道我做错了什么吗?

最佳答案

您设置了属性mysql_enable_utf8,因此您向接口(interface) promise 您将给它一个Perl 字符串。但是,这是 Latin1 编码中的八位字节缓冲区。

use Devel::Peek qw(Dump);
Dump "the N\xfcrburgring";
# FLAGS = (POK,READONLY,pPOK)
# PV = 0x208e4f0 "the N\374rburgring"\0

修复很简单。要么在没有 \x 转义的情况下标记文字字符,要么使用 utf8 pragma 告诉 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"]

... 或将八位字节解码为字符串。大多数时候你处理的不是文字,而是来自外部的数据,所以更好 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"]

关于mysql - 使用 Perl/DBI 在 MySQL 表中截断 utf-8 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7935934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com