使用utf8从perl脚本访问latin1 mysql数据库
我有一个使用 utf8
pragma 的 Perl 脚本,由于各种原因,它以 utf8 执行大部分操作是最实用的。但是,我需要访问 mysql 数据库,其中所有表都在 latin1 中。我该怎么做?
一点“伪代码”:
use utf8;
use DBI;
my $dbh = DBI->connect("DBI:mysql:$database;host=$server", $user, $pw);
my $sth = $dbh->prepare(
"SELECT recipe.ingredients
FROM recipe
WHERE recipe.id=?");
$sth->execute('rødgrød');
如果我删除 use utf8;
并将我的脚本保存在 latin1 中,这将按预期工作。
(我从来不需要插入到表中,只需从中读取,但我认为这并不重要。)
I have a perl script using the utf8
pragma, and for various reasons it is most practical that it does most of its operations in utf8. However, I need to access a mysql database, where all tables are in latin1. How should I do this?
A bit of 'pseudocode':
use utf8;
use DBI;
my $dbh = DBI->connect("DBI:mysql:$database;host=$server", $user, $pw);
my $sth = $dbh->prepare(
"SELECT recipe.ingredients
FROM recipe
WHERE recipe.id=?");
$sth->execute('rødgrød');
If I drop the use utf8;
and save my script in latin1, this works as expected.
(I never need to INSERT into the table, just read from it, but I don't suppose that really matters.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当连接到mysql时,你应该告诉你的脚本期望并提供UTF-8,所以你需要在连接时告诉它:
据我所知,最好在连接时告诉它,而不是事后告诉它。
When connecting to mysql, you should tell your script expects and provides UTF-8, so you need to tell it on connection:
AFAIK it is better to tell it on connection, not afterwards.
尝试将其设置为如下所示:
try setting it to something like this:
请注意,如果 Perl 源文件以 UTF-8 编码,则仅需要使用
utf8
pragma。另一方面,如果它是用 Latin1 编码的,则您不应该使用utf8
编译指示。那么rødgrød
是由七个 (Latin1) 还是九个 (UTF-8) 八位字节组成?与MySQL的交互与
utf8
设置无关,soulSurfer2010已经针对这个问题给出了正确的答案。Note that the
utf8
pragma is due exclusively if your Perl source file is encoded in UTF-8. If, on the other hand, it is encoded in Latin1, you should not be using theutf8
pragma. So isrødgrød
composed of seven (Latin1) or nine (UTF-8) octets?The interaction with MySQL is independent of the
utf8
setting, and soulSurfer2010 has given the right answer for that issue.