使用utf8从perl脚本访问latin1 mysql数据库

发布于 2024-11-04 08:56:51 字数 490 浏览 2 评论 0原文

我有一个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

篱下浅笙歌 2024-11-11 08:56:51

当连接到mysql时,你应该告诉你的脚本期望并提供UTF-8,所以你需要在连接时告诉它:

my $dbh = DBI->connect("DBI:mysql:$database;host=$server", $user, $pw, {mysql_enable_utf8 => 1 });

据我所知,最好在连接时告诉它,而不是事后告诉它。

When connecting to mysql, you should tell your script expects and provides UTF-8, so you need to tell it on connection:

my $dbh = DBI->connect("DBI:mysql:$database;host=$server", $user, $pw, {mysql_enable_utf8 => 1 });

AFAIK it is better to tell it on connection, not afterwards.

青衫负雪 2024-11-11 08:56:51

尝试将其设置为如下所示:

$dbh->{'mysql_enable_utf8'} = 1;
$dbh->do(qq{SET NAMES 'utf8';});

try setting it to something like this:

$dbh->{'mysql_enable_utf8'} = 1;
$dbh->do(qq{SET NAMES 'utf8';});
痴情换悲伤 2024-11-11 08:56:51

请注意,如果 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 the utf8 pragma. So is rø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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文