Villemoes
Villemoes

Reputation: 216

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

Upvotes: 2

Views: 1981

Answers (3)

w.k
w.k

Reputation: 8376

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.

Upvotes: 3

Lumi
Lumi

Reputation: 15274

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.

Upvotes: 0

snoofkin
snoofkin

Reputation: 8895

try setting it to something like this:

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

Upvotes: 1

Related Questions