使用perl DBI模块向mysql/ target=_blank class=infotextkey>mysql数据库写入中文和显示中文造成乱码的解决方法,感兴趣的朋友可以参考下。
主要用到如下的方法:
$dbh->do("SET character_set_client='gbk'");
$dbh->do("SET character_set_connection='gbk'");
$dbh->do("SET character_set_results='gbk'");
例子:
#!/bin/perl
use strict;
use warnings;
use DBI;
use Data::Dumper;
my $dbh = DBI->connect("DBI:mysql:database=ipofasbak;host=10.123.16.229","ipofas","sagacity", {'RaiseError' => 1,'AutoCommit'=>1});
$dbh->do("SET character_set_client='gbk'");
$dbh->do("SET character_set_connection='gbk'");
$dbh->do("SET character_set_results='gbk'");
#显示中文
my $sth = $dbh->prepare("select * from tb_pt_ai_def");
$sth->execute;
while (my @row = $sth->fetchrow_array) {
print "@row";
print "n";
}
$sth->finish;
#写入中文
eval{
$dbh->do("insert tb_pt_ai_def values('XLBH017',1 , 'IU1', '线路电流平均值', 0 ,1 , 0, 99999, 0, 0, 'A', 0, '2000-01-01 00:00:00', 0, 20,1, '' ,9,1, 2, 0)");
$dbh->do("insert tb_pt_ai_def values('XLBH017',2 , 'IU1', '线路电压平均值', 0 ,1 , 0, 99999, 0, 0, 'A', 0, '2000-01-01 00:00:00', 0, 20,1, '' ,9,1, 2, 0)");
};
if($@)
{
print "交易 aborted : $@";
$dbh->rollback();
}
$dbh->disconnect();