安装好MySQL8版本后,在安装目录会有mysql C++连接的头文件,静态库和动态库。如下图:
用VS2017新建C++控制台程序,根据安装的mysql是x86还是x64, 在项目属性中配置
- 包含mysql头文件目录:C:\Program Files\MySQL\MySQL Server 8.0\include
- 包含lib目录:C:\Program Files\MySQL\MySQL Server 8.0\lib
-
在程序运行后的exe目录放入libmysql.dll
代码:
/*
C++连接mysql
*/
#include <iostream>
#include "mysql.h"
using namespace std;
#pragma comment(lib, "libmysql.lib")
int main()
{
MYSQL mysql;
//初始化mysql
mysql_init(&mysql);
const char* host = "127.0.0.1";
const char* user = "root";
const char* pwd = "123456";
const char* db = "School";
//连接
if (!mysql_real_connect(&mysql, host, user, pwd, db, 3306, 0, 0))
{
cout << "mysql connected failed, " << mysql_error(&mysql) << endl;
}
else
{
cout << "mysql connected success" << endl;
}
MYSQL_RES* res; //查询结果
MYSQL_ROW row; //一条数据记录,二维数组
//查询
const char* sql = "select * from student";
mysql_query(&mysql, sql);
//获取结果
res = mysql_store_result(&mysql);
while (row = mysql_fetch_row(res))
{
cout << row[0] << " ";
cout << row[1] << endl;
//student表只有两个字段 id, name
}
mysql_free_result(res);
mysql_close(&mysql);
return 0;
}
运行结果:
来源:oschina
链接:https://my.oschina.net/u/4309139/blog/4253783