在Perl中使用UTF-8编码查询MySQL数据库

2008年6月18日 | 标签: , ,

Perl里提供了DBI这个模块来连接MySQL数据库,使得查询MySQL数据库特别方便。不过,很多人发现,如果MySQL数据库的某些表中使用了UTF-8编码,那查询的结果就成了“?”,为此不得不采用GB2312这样的编码。实际上,这个问题解决起来也很简单,就是在连接字段里面加上{‘mysql_enable_utf8′=>1}即可。例如下面的一小段示范代码:

use DBI;
use warnings;
use strict;
use utf8;
use bytes;

my $dbh = DBI->connect("DBI:mysql:database=yourdatabase;host=yourhost",
			"username", "password",
			{'RaiseError'=>1, 'mysql_enable_utf8'=>1})
			|| die "Cannot connect to database:".DBI->errstr;
my $sth=$dbh->prepare('SELECT * FROM onetable');
$sth->execute()||die "An error occurs while querying: ".$sth->errstr;
while(my @data=$sth->fetchrow_array()){
	for my $i(0..$#data) {
		print "$data[$i]\\t";
	}
	print "\\n";
}
$dbh->disconnect();
目前还没有任何评论.