【问题标题】:Perl and MySQL UTF-8 malformed characters after INSERT插入后的 Perl 和 MySQL UTF-8 格式错误的字符
【发布时间】:2016-02-09 12:07:09
【问题描述】:

我有一个 UTF-8 编码的 XML 文件。我使用Perl 解析文件(使用XML::Simple 模块)。我想将解析后的代码放入 MySQL 表中,它也编码了 utf8(确切地说是 utf8_generic_ci)。一切都很好,但有两个字符出错(通常是 ő 和 ű 及其大写对 ŐŰ)。

这是我的 perl 代码:

use strict;
use warning;
use utf8;
use XML::Simple;
use DBI;

my $db = DBI->connect("dbi:mysql:dbname=$dbname;host=$host;port=$port",
         $user, $passwd, {mysql_enable_utf8 => 1}) || die $DBI::errstr;

my $ref = XMLin("file.xml");

for ( my $i = 0; $i < scalar(@{$ref->{"PRODUCTS"}}); $i++ ) {
    my $name = $ref->{"PRODUCTS"}[$i]->{"NAME"};
    # some changes on the $name, for example removing whitespaces, etc.
    $db->do("INSERT INTO products (productname) VALUES ('".$name."');");
}

这是我的 mysql 表结构(SHOW CREATE TABLE products; 输出):

| products | CREATE TABLE `products` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `productname` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

我认为一切都在 UTF-8 中。如果我看到源 XML 文件,那么 őű 字符很好。但是在mysql插入之后他们出错了。其他口音也不错。

知道是什么问题吗?

【问题讨论】:

  • 在顶部附近添加:use open ':std', ':encoding(UTF-8)';

标签: mysql perl utf-8 character-encoding


【解决方案1】:

您的代码中有错字,应该是:

{ mysql_enable_utf8 => 1 }  

另外,你应该绑定 SQL 参数:

$db->do("INSERT INTO products (productname) VALUES (?)", undef, $name);

最后,this SO question 可能会帮助你

【讨论】:

  • 虽然您通常希望在从数据库中检索文本字符串时启用mysql_enable_utf8,但在检索 XML 文档时通常不希望启用它。 XML 解析器几乎总是期望字节作为输入而不是字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2014-05-20
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
相关资源
最近更新 更多