标签:
使用mysql++读取mysql数据库,数据表中字符集为utf8,但是读取的时候中文字符串不能够正常显示。下面是测试程序:
#include <iostream> #include <mysql++/mysql++.h> using namespace mysqlpp; using namespace std ; int main(){ 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; string str =string(row[2].c_str()); cout<<str<<endl; } } }catch (BadQuery er){ cout<<"Error:"<<er.what()<<endl; return -1; }catch (const BadConversion &er){ cout << "Conversion error: " << er.what() << endl << "\tretrieved data size: " << er.retrieved << ", actual size: " << er.actual_size << endl; return -1; }catch (const Exception &er){ // Catch-all for any other MySQL++ exceptions cout << "Error: " << er.what() << endl; return -1; } return 0; }
可见输出有问题,但是我们的数据表字符集设置没有问题。输出创建数据表的sql语句。
show create table stock_pool ; stock_pool | CREATE TABLE `stock_pool` ( `id` int(11) NOT NULL AUTO_INCREMENT, `stock_id` varchar(255) NOT NULL, `stock_name` varchar(255) NOT NULL, `state` int(11) NOT NULL, `can_lever` int(11) NOT NULL, `serial` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 |
解决方案很简单,设置mysql连接参数,设置字符集为utf8,如下所示:
#include <iostream> #include <mysql++/mysql++.h> using namespace mysqlpp; using namespace std ; int main(){ 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; string str =string(row[2].c_str()); cout<<str<<endl; } } }catch (BadQuery er){ cout<<"Error:"<<er.what()<<endl; return -1; }catch (const BadConversion &er){ cout << "Conversion error: " << er.what() << endl << "\tretrieved data size: " << er.retrieved << ", actual size: " << er.actual_size << endl; return -1; }catch (const Exception &er){ // Catch-all for any other MySQL++ exceptions cout << "Error: " << er.what() << endl; return -1; } return 0; }
运行输出:
平安银行 国农科技 陕国投A 宝钛股份 中航地产
又可以愉快的玩耍了!
标签:
原文地址:http://www.cnblogs.com/zhoudayang/p/5463217.html