代码改变世界

mysql++使用

2015-10-15 00:02  youxin  阅读(2181)  评论(0编辑  收藏  举报

Mysql++是官方发布的、一个为MySQL设计的C++语言的API。Mysql++为Mysql的C-Api的再次封装,它用STL(Standard Template Language)开发并编写,并为C++开发者提供像操作STL容器一样方便的操作数据库的一套机制。其官方API介绍:MySQL++ Reference Manual

与JDBC一样,先建立连接Connection,创建Query,执行操作获得结果。

SimpleResult Query::store()进行更新、删除、创建等操作,SimpleResult代表执行状态,查询是否成功、影响了多少行。

StoreQueryResult Query::store():最常用。StoreQueryResult继承vector<mysqlpp::Row>,Row类似于vector<string>,表示一行中各列的数据。使用可以result[1][4]或result[2]["price"]。

UseQueryResult Query::use(),大结果查询,UserQueryResult是iterator,一次只能获得一个行结果,不停地next直到结束为止。

简单示例

#include <mysql++.h>
// Connect to the sample database.
mysqlpp::Connection conn(false);
if (conn.connect(db, server, user, pass)) {
    // Retrieve a subset of the sample stock table set up by resetdb
    // and display it.
    mysqlpp::Query query = conn.query("select item from stock");
    if (mysqlpp::StoreQueryResult res = query.store()) {
       cout << "We have:" << endl;
       for (size_t i = 0; i < res.num_rows(); ++i) {
            cout << '\t' << res[i][0] << endl;
         }
     }
     else {
        cerr << "Failed to get item list: " << query.error() << endl;
        return 1;
     }
     return 0;
}
else {
    cerr << "DB connection failed: " << conn.error() << endl;
    return 1;
}