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 3 years have passed since last update.

MariaDB に perl で接続した時の文字化け対策

Last updated at Posted at 2020-06-21

次のページを参考にしました。
MySQL から取得した文字が化けるのは DBD::MySQL のせいだった

接続後に次の SQL を実行すれば解決します。

SET NAMES utf8

テストプログラム

maria_read.pl
# ! /usr/bin/perl
#
#	maria_read.pl
#
#					Jun/21/2020
#
# -----------------------------------------------------------------------
use	strict;
use	warnings;
use	utf8;
use	Encode;
use	DBI;
#
# -----------------------------------------------------------------------
sub mysql_utf8_proc
{
	my $db = $_[0];
	my $sth = $db->prepare("SET NAMES utf8");
	$sth->execute;
}

# -----------------------------------------------------------------------
sub sql_show_proc
{
	my $db = $_[0];

	print "*** sql_show_proc ***\n";

	my $sth = $db->prepare("SELECT * FROM cities");
	$sth->execute;
	my $num_rows = $sth->rows;

	for (my $it=0; $it<$num_rows; $it++)
		{
		my @a = $sth->fetchrow_array;
		print "$a[0]\t$a[1]\t$a[2]\t$a[3] \n";
		}

	$sth->finish;
}
# -----------------------------------------------------------------------
print	(encode ('utf-8',"*** 開始 ***\n"));
#
my $constr='DBI:mysql:city:localhost';
my $user = 'scott';
my $passwd = 'tiger123';
#
my $dbi=DBI->connect($constr, $user, $passwd);
sql_show_proc($dbi);
#
#
mysql_utf8_proc($dbi);
sql_show_proc($dbi);
#
$dbi->disconnect;
#
print	(encode ('utf-8',"*** 終了 ***\n"));
# -----------------------------------------------------------------------

実行結果

$ ./maria_read.pl 
*** 開始 ***
*** sql_show_proc ***
t3321	??	128763	1950-10-23 
t3322	??	3412300	2020-06-07 
t3323	??	753241	1950-01-02 
t3325	??	769358	1950-08-14 
t3326	??	865792	1950-09-12 
t3328	??	3298700	2020-06-07 
t3329	??	276951	1950-10-02 
*** sql_show_proc ***
t3321	岡山	128763	1950-10-23 
t3322	倉敷	3412300	2020-06-07 
t3323	津山	753241	1950-01-02 
t3325	笠岡	769358	1950-08-14 
t3326	井原	865792	1950-09-12 
t3328	高梁	3298700	2020-06-07 
t3329	新見	276951	1950-10-02 
*** 終了 ***

接続時に DBIのオプションを設定しても解決します。

my $dbi=DBI->connect($constr, $user, $passwd,{mysql_enable_utf8 => 1});
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?