使用MySQLpp访问MySQL
昨天忘了在看什么的时候发现了在/usr/include/中有个mysql++的文件夹,google之发现原来这个是mysqlpp,一个C++的用来访问MySQL的第三方的库。google到的提供支持的是这个网站http://tangentsoft.net/mysql++/。上面有详细的文档。貌似这个也是有官方支持的,在mysql的官网的emaillist中发现好多关于这个库的。
之前也有弄过官网的mysql connector for c++,但是弄了好久没有弄好,到处搜解决方案,不过网上关于mysql C API的很多,关于这个c++ connector的很少。后来发现据说是官网上的这么一句话的原因:
One problem that can occur is when the tools you use to build your application are not compatible with the tools used to build the binary versions of MySQL Connector/C++. Ideally, you need to build your application with the same tools that were used to build
the MySQL Connector/C++ binaries.
但是最后也没有弄好。现在用这个mysqlpp,首先看名字就觉得很优雅,使用起来也确实很好用。文档齐全,平台支持好(我只在ubuntu下使用过,其他平台没有使用过),关键是使用起来真的很方便。这个库是在C API上的一层包装,因此必须有C API,也就是装了mysql server之后在/usr/include/mysql下的一堆文件(以及相应的.lib.so.a文件)。
开始使用MySQLpp
这里将我刚开始接触的一些问题写一下,其实也没碰到多少问题,很容易上手。在文档中copy了一个例子:build and run,出现了下面的错误:
/usr/include/mysql++/common.h|131|致命错误: mysql_version.h:没有那个文件或目录|
点了错误后,code blocks跳到了源文件common.h,定位到下面的第4行。我又找了找,在/usr/include/mysql++下没有发现mysql_version.h文件,于是我猜就是要使用mysql/mysql_version.h了,于是就Ctrl+F MYSQLPP_MYSQL_HEADERS_BURIED,找了半天没找到。于是google,发现要在自己写的文件中#define,于是解决问题。后来看文档中貌似也是这么个意思。
#if defined(MYSQLPP_MYSQL_HEADERS_BURIED) # include <mysql/mysql_version.h> #else # include <mysql_version.h> #endif第二个问题就是各种类似于下面的:
/testCB/mysql++_test/test_main.cpp|9|undefined reference to `mysqlpp::Connection::Connection(bool)"|这个显然是库linker没有找到库么,于是add linker library /usr/lib/libmysqlpp.so之后解决问题。然后就顺利的执行了。
与Python的MySQLdb使用对比
我一直觉得Python的代码比较简洁,并且库也比较实用(其实是废话),于是我经常拿这些库和Python的比较。下面我比较一下mysqlpp与python中的MySQLdb。
import MySQLdb conn=MySQLdb.connect(host="localhost",user="root",passwd="xxxx",charset="utf8") cursor=conn.cursor() conn.select_db("test") count=cursor.execute("SELECT text FROM test_schema limit 2") results=cursor.fetchmany(count)#unicode print results[0][0] conn.close()
这么一段代码就完成了数据库的访问,下面这一段是使用mysqlpp的访问
#define MYSQLPP_MYSQL_HEADERS_BURIED #include <mysql++/mysql++.h> #include <iostream> #include <vector> int main(int argc, char *argv[]) { mysqlpp::Connection conn(true); conn.set_option(new mysqlpp::SetCharsetNameOption("utf8")); conn.connect("test", "localhost", "root", "xxxx", 3306); mysqlpp::Query query=conn.query("select text from test_schema limit 2"); mysqlpp::StoreQueryResult res = query.store(); std::cout<<res.num_rows()<<std::endl; for (size_t i = 0; i < res.num_rows(); ++i) { std::cout << "1" << res[i][0] << std::endl; } return 0; }
是不是感觉如出一辙呢?恩,以后就用这个库了。值得一提的是,上面set_option的参数貌似必须是new的,如果自己定义了一个这样的对象然后传入引用,会出现内存错误貌似。
- 上一篇: php利用curl实现多进程下载文件类
- 下一篇: 26. PHP 文件打开/读取/读取