Solve perl + mysql + mongodb Chinese garbage problem

Recently, the use of data to guide perl mongodb process, found mongodb credited to the Chinese garbled data. Why use perl import data into mongodb in? Too many companies cms mysql database using multi-table joins and performance getting lower and lower, and decided to mysql data redundancy to a mongodb in order to reduce the Gregorian cms database. That what way to import data into mongodb in it? Using the shell operation mongodb inconvenient to use php feeling is not very efficient, the final choice of Chinese perl appear garbled in the process of using perl guide data, simple restore it here live Chinese garbled mongodb appear.. Mongodb Chinese garbled code is as follows:
# 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});
 }
Found mongodb distortion perl run results, mongodb inside in Chinese distortion screenshot follows: [caption id = "attachment_2384" align = "aligncenter" width = "729"] perl + mongodb Chinese distortion [/ caption] mysql inside taken out data gbk, stored mongodb not decode time. After modifying the code for the following issues are resolved mongodb no Chinese garbled code is as follows:
# 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});
 }
  FIG perl results are as follows, is not less mongodb Chinese distortion: [caption id = "attachment_2385" align = "aligncenter" width = "612"] perl + mongodb distortion solution [/ Caption]   encode and decode Usage
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));
Summary, with particular attention to be inserted into the encoded data mongodb, this situation not to occur again please indicate the source:. Http: //www.ttlsa.com/html/2380.html

Reproduced in: https: //my.oschina.net/766/blog/211008

Guess you like

Origin blog.csdn.net/weixin_34005042/article/details/91493035