1. VS2022 控制台工程,Debug X86模式,字符集选用Multi-Byte
2. 把MySQL的头文件和库文件路径加进工程。
3. 把MySQL的库目录中的动态链接库libmysql.dll 复制到工程的当前工作目录下
4. 返回值中有NULL要注意转换
头文件路径:

库文件路径:

运行结果:

测试程序:MySQLTest.cpp
// MySQLTest.cpp : This file contains the 'main' function. Program execution begins and ends there.
//1. VS2022 控制台工程,Debug X86模式,字符集选用Multi-Byte
//2. 把MySQL的头文件和库文件路径加进工程。
//3. 把MySQL的库目录中的动态链接库libmysql.dll 复制到工程的当前工作目录下
//4. 返回值中有NULL要注意转换
//
// XGZ 2022-07-16 SZ
#include <WinSock2.h>
#include <mysql.h>
#include <string>
#include <vector>
using namespace std;
#pragma comment(lib,"libmysql.lib")
int main()
{
MYSQL* conn;
MYSQL_ROW row;
MYSQL_RES* res;
int nrow;
int ncolum;
vector <string> data1;
conn = mysql_init(NULL);
if (!conn)
{
printf("/n <ERR> mysql_init failed!");
return -1;
}
//本地连接到test数据库
conn = mysql_real_connect(conn, "127.0.0.1", "root", "root123", "test", 0, NULL, 0);
if (conn)
{
printf("/n<OK>mysql_real_connect success!");
}
else
{
printf("/n<ERR>mysql_real_connect failed!");
return -1;
}
//查询test数据库user表
mysql_query(conn, "select * from user");
res = mysql_store_result(conn);
if (NULL == res)
{
return 0;
}
ncolum = mysql_num_fields(res); //xgz 查表结果的列数
nrow = 0;
//保存读到的数据
while (row = mysql_fetch_row(res))
{
for (int rols = 0; rols < ncolum; rols++)
{
if(NULL == row[rols])
{
data1.push_back("NULL"); //xgz 如果返回值是NULL,就换成字符串NULL
}
else
{
data1.push_back(row[rols]);
}
}
nrow++;
}
//处理(打印)读取的数据
printf("/n=== Result row= %d, colum=%d ===/n",nrow,ncolum);
for (int i = 0; i < nrow; i++)
{
for (int j = 0; j < ncolum; j++)
{
printf("/t%s", data1.at(i * ncolum + j).c_str());
}
printf("/n");
}
return 0;
}
原创文章,作者:506227337,如若转载,请注明出处:https://blog.ytso.com/tech/bigdata/274729.html