演示表
mysql -u root -p 123456
select * from mysql_test.test01;
+---------+-----------+----------+
| test_id | test_name | test_sex |
+---------+-----------+----------+
| 0 | XiaoMing | 0 |
| 1 | ZhangShan | 0 |
| 2 | LiShi | 1 |
| 3 | XiaoHong | 1 |
| 4 | WangEr | 0 |
+---------+-----------+----------+
test_sex 0 为男 1 为女
mysql 头文件引用
#include "mysql.h"
#pragma comment(lib, "../lib/libmysql.lib")
连接mysql
MYSQL _mydata;
//初始 mysql 结构体
if (NULL == mysql_init(&_mydata))
{
printf("mysql_init failed!\n");
return 0;
}
//初始化数据库
if (0 !=mysql_library_init(0,NULL,NULL))
{
//lib 初始化失败
printf("mysql_library_init failed!\n");
return 0;
}
//连接数据库
if (mysql_real_connect(&_mydata, "localhost", "root", "123456", "mysql_test", 3306, NULL, 0) == NULL)
{
printf("mysql connect failed!\n");
return 0;
}
printf("mysql connect succeed!\n");
查询
查询 XiaoHong 用户的 test_id(ID) 和 test_sex(性别)
char _buf[] = "select test_id,test_sex from test01 where test_name='XiaoHong'";
//执行 sql 语句
if (0 != mysql_real_query(&_mydata, _buf, sizeof(_buf)))
{
printf("mysql_real_query failed!\n");
return 0;
}
MYSQL_RES *_myres = mysql_store_result(&_mydata);//将全部数据读入缓存区
MYSQL_ROW _myrow = mysql_fetch_row(_myres);//读取缓存数据
int _id = 0;
while (_myrow != NULL)
{
_id = atoi(_myrow[0]);
if (_myrow[1])
printf("test_id = %d | test_sex = 女\n", _id);
else
printf("test_id = %d | test_sex = 男\n", _id);
_myrow = mysql_fetch_row(_myres);//循环读取
}
mysql_free_result(_myres);//释放缓存区数据 防止内存泄漏
修改
修改 LiShi 用户的 test_sex(性别) 为 男
char _buf[] = "update test01 set test_sex=0 where test_name='LiShi'";
//执行 sql 语句
if (0 != mysql_real_query(&_mydata, _buf, sizeof(_buf)))
{
printf("mysql_real_query failed!\n");
return 0;
}
删除
删除 test_id(ID) 为 4 的数据
char _buf[] = "delete from test01 where test_id='4'";
//执行 sql 语句
if (0 != mysql_real_query(&_mydata, _buf, sizeof(_buf)))
{
printf("mysql_real_query failed!\n");
return 0;
}
关闭mysql连接
mysql_close(&_mydata);//关闭 mysql 连接