INSERT后Perl和MySQL UTF-8格式错误的字符

时间:2015-11-08 21:08:26

标签: mysql perl utf-8 character-encoding

我有一个UTF-8编码的XML文件。我使用Perl来解析文件(使用XML::Simple模块)。我希望将解析后的代码放入MySQL表中,编码utf8(正好是utf8_generic_ci)。一切都很好,但是两个角色出错了(tip and和ű用他们的大写对ŐŰ)。

这是我的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插入后他们出错了。其他口音很好。

知道这是什么问题吗?

1 个答案:

答案 0 :(得分:1)

您的代码中有拼写错误,应该是:

{ mysql_enable_utf8 => 1 }  

此外,您应该绑定SQL参数:

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

最后,this SO question可以帮助你