Using mysql++ to read the MySQL database, the character set in the data table is UTF8, but the Chinese string cannot be displayed properly when reading. Here is the test program:
#include <iostream>#include<mysql++/mysql++.h>using namespaceMYSQLPP;using namespacestd;intMain () {Try{Connection conn (false); Conn.connect ("Stock","localhost","Root"); Query Query=conn.query ("SELECT * from Stock_pool"); if(Storequeryresult res =Query.store ()) { for(Auto it = Res.begin (); it!=res.end (); it++) {row row= *it; stringstr =string(row[2].c_str ()); cout<<str<<Endl; } } }Catch(Badquery er) {cout<<"Error:"<<er.what () <<Endl; return-1; }Catch(ConstBadconversion &er) {cout<<"Conversion Error:"<< er.what () << Endl <<"\tretrieved data size:"<< er.retrieved <<", actual size:"<< er.actual_size <<Endl; return-1; }Catch(ConstException &er) { //Catch-all for any other mysql++ exceptionscout <<"Error:"<< er.what () <<Endl; return-1; } return 0;}
There is a problem with the visible output, but there is no problem with our data table character set. Output the SQL statement that created the data table.
Show create table Stock_pool; Stock_pool | CREATE TABLE ' Stock_pool ' ( ' id ' int (one) not null auto_increment, ' stock_id ' varchar (255) NOT NULL, ' Stock_ Name ' varchar (255) NOT NULL, ' state ' int (one) not null, ' can_lever ' int (one) not NULL, ' serial ' int (one) NOT NULL , PRIMARY KEY (' id ')) engine=innodb auto_increment=30 DEFAULT Charset=utf8 |
The solution is simple, set the MySQL connection parameter, set the character set to UTF8, as follows:
#include <iostream>#include<mysql++/mysql++.h>using namespaceMYSQLPP;using namespacestd;intMain () {Try{Connection conn (false); conn.set_option ( new Mysqlpp::setcharsetnameoption ("UTF8")); Conn.connect ("Stock","localhost","Root"); Query Query=conn.query ("SELECT * from Stock_pool"); if(Storequeryresult res =Query.store ()) { for(Auto it = Res.begin (); it!=res.end (); it++) {row row= *it; stringstr =string(row[2].c_str ()); cout<<str<<Endl; } } }Catch(Badquery er) {cout<<"Error:"<<er.what () <<Endl; return-1; }Catch(ConstBadconversion &er) {cout<<"Conversion Error:"<< er.what () << Endl <<"\tretrieved data size:"<< er.retrieved <<", actual size:"<< er.actual_size <<Endl; return-1; }Catch(ConstException &er) { //Catch-all for any other mysql++ exceptionscout <<"Error:"<< er.what () <<Endl; return-1; } return 0;}
Run output:
Ping An state agricultural technology Shaanxi Investment a Bao titanium shares Avic Real Estate
It's fun to play again!
MySQL + + Chinese garbled problem