本文用的是MySQL 5.5,它自带了MySQL Connector C++ 1.1.0。
这个connector不好使,我用的win8 pro x64系统,和visual studio 2012,至少在这个环境下不好使,报0xc015002错误。
请下载最新版的,本文用的是MySQL Connector C++ 1.1.1(x86)。编译环境和Connector必须是一样的架构,同是x86,或者同是x64,本文同是x86。
不得不说MySQL Connector不给力,缺库缺文件要自己补上。
然后在VS中把include目录中添加boost目录,和Connector C++中的include目录
附加库目录加上Connector C++中的lib/opt目录
在工程属性链接器的输入中添加mysqlcppconn.lib和mysqlcppconn-static.lib
把sqlstring.h,以及connector lib/opt目录下的mysqlcppconn.dll,MSVCP90.dll,MSVCR90.dll复制到工程目录下(sqlstring和头文件放在一起,dll和生成的debug版的exe放在一起,dll也可以放在system32下)
Connector中的config.h和vc中的头文件stdint.h的int8_t有重定义error C2371,所以去config.h中注释掉int8_t的内容
最后用如下代码就可以跑起
代码是哪抄来的忘记了,MySQL connector的文档中也有这些代码,介绍了几个例子和API的使用
#include "mysql_connection.h"#include"mysql_driver.h"#include#include#include#include#include
using namespacesql;using namespacestd;#pragma comment(lib,"mysqlcppconn.lib")
#pragma comment(lib,"mysqlcppconn-static.lib")
voidRunConnectMySQL()
{
sql::mysql::MySQL_Driver*driver =NULL;
sql::Connection*con =NULL;
sql::Statement*state =NULL;
sql::ResultSet*result =NULL;try{
driver=sql::mysql::get_mysql_driver_instance();
con= driver->connect("tcp://127.0.0.1:3306","root","123456");//连接数据库
state = con->createStatement();
state->execute("use test");
result = state->executeQuery("select * from a");
}catch(sql::SQLException & ex)//如果上面有错就捕获这个异常
{
cout<
}while(result->next())
{
cout<getInt("id")<
}
state->close();
}voidmain()
{
RunConnectMySQL();
getchar();
;
}