0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perl の DBI で EUC_JP の MariaDB のデータを読み込んだ時の文字化け

Posted at

文字コードを EUC_JP としたMariaDB から下記のプログラムを実行した時に文字化けをする問題です。

Ubuntu 20.04 で実行した場合は文字化けが発生しません。

mojibake_aa.png

Arch Linux, RaspberryPi では文字化けします。

mojibake_bb.png

city_read.pl
# ! /usr/bin/perl
#
#	city_read.pl
#
#					Jul/04/2020
#
# -----------------------------------------------------------------------
use	strict;
use	warnings;
use	DBI;
#
# -----------------------------------------------------------------------
sub get_date_mod_proc
{
	my ($mday,$mon,$year) = (localtime (time))[3..5];
	$mon += 1;
	$year += 1900;
	my $date_mod = "$year-$mon-$mday";

	return $date_mod;
}

# -----------------------------------------------------------------------
print STDERR "*** city_read.pl *** start ***\n";
my $date_mod = get_date_mod_proc();
print STDERR $date_mod . "\n";
#
my $host = 'example.com';
my $constr='DBI:mysql:database=city:host=' . $host;
my $user = '******';
my $passwd = '******';
#
my $dbi=DBI->connect($constr, $user, $passwd);

my $sql = "select distinct Name from cities";
my $sth = $dbi->prepare($sql);
$sth->execute;
my $num_rows = $sth->rows;


print "Content-Type: text/html\n\n";

print "<!DOCTYPE html>\n";
print "<html lang=\"ja\">\n";
print "<head>\n";
print "<meta http-equiv=\"CONTENT-TYPE\" content=\"text/html; charset=EUC-JP\" />\n";
print "<title>mariadb_read.pl</title>\n";
print "</head>\n";
print "<body>\n";

print "*** city_read.pl *** start ***<br />\n";
print $date_mod . "<br />\n";
print $host . "<p />\n";
print "num_rows =" . $num_rows . "<p />\n";

for (my $it=0; $it<$num_rows; $it++)
	{
	my @aa = $sth->fetchrow_array;
	my $pp = $aa[0];
	print "$pp<br />\n";
	}

print "<p />";
print "*** Jul/04/2020 ***<p />\n";
print "*** end ***<p />\n";
print "</body>\n";
print "</html>\n";
#
my $rc = $sth->finish();
$dbi->disconnect();
#
print STDERR "*** city_read.pl *** end ***\n";
# -----------------------------------------------------------------------

Arch と RaspberryPi で文字化けしないようにするには、connect 後に次のコードを入れます。

my $dbi=DBI->connect($constr, $user, $passwd);
$dbi->prepare("SET NAMES ujis")->execute;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?