最近接触到数据库,发现用java的jdbc连接数据库很简单,c++就很麻烦了。在网上找了很多资料,大致有两种方法:1、通过mysql的C api进行操作;2、通过mysql的Connector C++ 1.1.3进行操作。第一种方法到现在都还没有实现,不过在今天用第二种方法完成了数据库的连接。具体如下:
1、下载mysql官方的 connector API:http://dev.mysql.com/downloads/connector/cpp/ 解压或者安装
2、boost:http://netix.dl.sourceforge.net/project/boost/boost/1.60.0/boost_1_60_0.zip 解压
3、用vs新建工程,在项目属性中进行如下操作:
a、在VC++目录中的包含目录加入
b、再在VC++目录的库目录中加入
c、在链接器->常规->附加库目录中加入
d、在链接器->输入->附加依赖项中加入
e、在C/C++的附加包含目录中写入
f、Right Click project, Properties->Configuration Properties->Linker->General->Additional Library Directories and add the directory that has the MySQL libraries
D:\mysql-connector-c++-noinstall-1.1.7-winx64\mysql-connector-c++-noinstall-1.1.7-winx64\lib ,to avoid the error
"fatal error LNK1104: cannot open file 'mysqlcppconn.lib'"
g、 如果是64位的 将平台改成x64
h 、将mysqlcppconn.dll文件和之前所输入的libmysql.dll 复制到Windows\system32 文件夹底下。
4、代码测试
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include "mysql_driver.h"
#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/statement.h"
#include "cppconn/prepared_statement.h"
#include "cppconn/metadata.h"
#include "cppconn/exception.h"
using namespace std;
using namespace sql;
int main()
{
sql::mysql::MySQL_Driver *driver = 0;
sql::Connection *conn = 0;
try
{
driver = sql::mysql::get_mysql_driver_instance();
conn = driver->connect("tcp://localhost:3306/dbname", "username", "password");//contest是自己的一个数据库,root是mysql的登录名,123是自己的密码
//请自行修改
cout << "连接成功" << endl;
}
catch (exception ex)
{
cout << "连接失败" << endl;
}
system("pause");
return 0;
}
ref:
http://blog.youkuaiyun.com/CQU_LiuHC/article/details/50923907
http://stackoverflow.com/questions/8755131/fatal-error-lnk1104-cannot-open-file-mysqlcppconn-lib