最近,使用perl导数据到mongodb过程中,发现存入到mongodb的中文数据乱码.
为什么要使用perl导入数据到mongodb中?
公司cms使用的mysql数据库太多多表连接并且性能越来越低,于是决定将mysql的数据冗余一份到mongodb中,以降低cms数据库的阳历. 那用什么方式导入数据到mongodb中呢?使用shell操作mongodb不方便、使用php感觉效率不是很高、最后选择了perl. 在使用perl导数据的过程中出现中文乱码, 这边简单还原一下mongodb出现中文乱码的现场.文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
mongodb中文乱码代码如下:文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
# cat /root/ttlsa_com.pl #!/usr/bin/perl use DBI; use MongoDB; use Encode; my $dbh = DBI->connect("DBI:mysql:database=cms;host=192.168.50.213","root","test11", {'RaiseError' => 1}) or die "error"; $dbh->do("set names gbk");//这部一定要做,否则从mysql取出来的数据就是乱码, my $sth = $dbh->prepare("select title from cms limit 10 ) or die $dbh->errstr; $sth->execute() or die $sth->errstr; while(my @data = $sth->fetchrow_array()) { my $title = $data[0]; $collection->insert({ title => $title}); }
发现mongodb出现乱码
perl运行结果,mongodb里面的中文是乱码,截图如下:文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/

perl + mongodb中文乱码
mysql里面取出来的数据时gbk,存储到mongodb没有decode一次。修改为如下代码之后问题得到解决文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
mongodb无中文乱码代码如下:文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
# cat /root/ttlsa_com.pl #!/usr/bin/perl use DBI; use MongoDB; use Encode; my $dbh = DBI->connect("DBI:mysql:database=cms;host=192.168.50.213","root","test11", {'RaiseError' => 1}) or die "error"; $dbh->do("set names gbk"); my $sth = $dbh->prepare("select title from cms limit 10 ) or die $dbh->errstr; $sth->execute() or die $sth->errstr; while(my @data = $sth->fetchrow_array()) { my $title = decode("gbk",$data[0]); $collection->insert({ title => $title}); }
文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
perl运行结果如下图,以下mongodb中文不是乱码:文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/

perl + mongodb乱码解决
文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
encode与decode用法文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
use Encode; gbk转uft-8: $data = encode("utf-8",decode("gbk",$data)); 或者 $data = encode_utf8(decode("gbk",$data)); utf-8转gbk: $data = encode("gbk", decode("utf8", $data)); uft-8转gb2312: $data = encode("gb2312", decode("utf8", $data));
总结,尤其注意要插入到mongodb的数据的编码,不要再次出现这种情况.文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
转载请注明出处:https://www.ttlsa.com/html/2380.html文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/文章源自运维生存时间-https://www.ttlsa.com/perl/perl-mysql-mongodb-luanma/
1F
ensnfklnf