一.步骤
平台改为X64(win32的话配置后会不正确)
右键项目属性 -> C/C++ -> 常规->附加包含目录。
添加你的mysql安装目录下的include目录,例如我的是:D:\WAMP\mysql8\include:项目属性 -> 链接器 -> 常规-> 附加库目录。添加MySQL安装目录下的lib目录,例如我的是 D:\WAMP\mysql8\lib。
项目属性 -> 链接器 -> 输入 -> 附加依赖项。添加libmysql.lib文件。
将 D:\WAMP\mysql8\lib 下的libmysql.dll复制粘贴到C++项目.x64\DEBUG\中。
二.测试(注意将数据库密码等设置为自己本地的配置)
#include "stdio.h"
#include "mysql.h"
int main()
{
MYSQL* con; //= mysql_init((MYSQL*) 0);
MYSQL_RES* res;
MYSQL_ROW row;
char tmp[400];
//database configuartion
char dbuser[30] = "root";
char dbpasswd[30] = "20010502"; // it must be changed
char dbip[30] = "localhost";
char dbname[50] = "buct";
char tablename[50] = "user_approve";
char* query = NULL;
int x;
int y;
int rt;//return value
unsigned int t;
int count = 0;
con = mysql_init((MYSQL*)0);
if (con != NULL && mysql_real_connect(con, dbip, dbuser, dbpasswd, dbname, 3306, NULL, 0)) {
if (!mysql_select_db(con, dbname)) {
printf("Select successfully the database!\n");
con->reconnect = 1;
query = (char*)(*"set names \'GBK\'");
rt = mysql_real_query(con, query, strlen(query));
if (rt) {
printf("Error making query: %s !!!\n", mysql_error(con));
}
else {
printf("query %s succeed!\n", query);
}
}
}
else {
MessageBoxA(NULL, "Unable to connect the database,check your configuration!", "", NULL);
}
//sprintf(tmp, "insert into %s values(%s,%d,%d)", tablename, "null", x, y); //注意如何向具有自增字段的数据库中插入记录
sprintf(tmp, "insert into bl values(null,'x','x','x','x')");
rt = mysql_real_query(con, tmp, strlen(tmp));
if (rt)
{
printf("Error making query: %s !!!\n", mysql_error(con));
}
else
{
printf("%s executed!!!\n", tmp);
}
sprintf(tmp, "select * from %s", tablename);
rt = mysql_real_query(con, tmp, strlen(tmp));
if (rt)
{
printf("Error making query: %s !!!\n", mysql_error(con));
}
else
{
printf("%s executed!!!\n", tmp);
}
res = mysql_store_result(con);//将结果保存在res结构体中
while (row = mysql_fetch_row(res)) {
for (t = 0; t < mysql_num_fields(res); t++) {
printf("%s ", row[t]);
}
printf(".............\n");
count++;
}
printf("number of rows %d\n", count);
printf("mysql_free_result...\n");
mysql_free_result(res);
mysql_close(con);
system("pause");
return 0;
}
三.参考
C/C++连接MySql数据库
C++连接MySQL数据库
C++实现对MySQL数据库的连接,以及增删改查
欢迎在评论区中进行批评指正,转载请注明来源,如涉及侵权,请联系作者删除。