Sunday, December 2, 2012

Using PostgreSQL and Unicode via Perl on Debian Linux

Here was how I connected to a PostgreSQL database via Perl. I handled the Unicode characters such as Chinese or Korean.

pg_enable_utf8 should be used.



#!/usr/bin/perl -w

# load module
use DBI;
use strict;
use utf8;
use encoding "utf-8";

# connect
my $d = DBI->connect("DBI:Pg:dbname=s;host=/tmp", "postgres","", {pg_enable_utf8 => 1, 'RaiseError' => 1});


 sub getIt 

{
      my   $rows = $d->do("SET NAMES 'UTF8'");
   #      print "$rows row(s) affected\n";
   if ( $rows == 0 ) {


      my $string = 'a';

      my $sth =  $d->prepare("SELECT count(*) FROM a WHERE id=$_[0] AND s=\$\$$string\$\$");

      $sth->execute();

# iterate through resultset
# print values

while(my $ref = $sth->fetchrow_hashref()) 

{
    print  $ref->{'count'}  ;

} # while(my $ref = $sth->fetchrow_hashref())

} # getIt

# clean up
$d->disconnect();

No comments:

RSS