简体   繁体   中英

Accessing latin1 mysql database from perl script using utf8

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.)

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.

try setting it to something like this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM