当前位置:   article > 正文

c++ 操作 mysql_ieg123

ieg123

演示表

  1. mysql -u root -p 123456
  2. select * from mysql_test.test01;
  3. +---------+-----------+----------+
  4. | test_id | test_name | test_sex |
  5. +---------+-----------+----------+
  6. | 0 | XiaoMing | 0 |
  7. | 1 | ZhangShan | 0 |
  8. | 2 | LiShi | 1 |
  9. | 3 | XiaoHong | 1 |
  10. | 4 | WangEr | 0 |
  11. +---------+-----------+----------+
  12. test_sex 0 为男 1 为女

mysql 头文件引用

  1. #include "mysql.h"
  2. #pragma comment(lib, "../lib/libmysql.lib")

连接mysql

  1. MYSQL _mydata;
  2. //初始 mysql 结构体
  3. if (NULL == mysql_init(&_mydata))
  4. {
  5. printf("mysql_init failed!\n");
  6. return 0;
  7. }
  8. //初始化数据库
  9. if (0 !=mysql_library_init(0,NULL,NULL))
  10. {
  11. //lib 初始化失败
  12. printf("mysql_library_init failed!\n");
  13. return 0;
  14. }
  15. //连接数据库
  16. if (mysql_real_connect(&_mydata, "localhost", "root", "123456", "mysql_test", 3306, NULL, 0) == NULL)
  17. {
  18. printf("mysql connect failed!\n");
  19. return 0;
  20. }
  21. printf("mysql connect succeed!\n");

查询

查询 XiaoHong 用户的 test_id(ID) 和 test_sex(性别)

  1. char _buf[] = "select test_id,test_sex from test01 where test_name='XiaoHong'";
  2. //执行 sql 语句
  3. if (0 != mysql_real_query(&_mydata, _buf, sizeof(_buf)))
  4. {
  5. printf("mysql_real_query failed!\n");
  6. return 0;
  7. }
  8. MYSQL_RES *_myres = mysql_store_result(&_mydata);//将全部数据读入缓存区
  9. MYSQL_ROW _myrow = mysql_fetch_row(_myres);//读取缓存数据
  10. int _id = 0;
  11. while (_myrow != NULL)
  12. {
  13. _id = atoi(_myrow[0]);
  14. if (_myrow[1])
  15. printf("test_id = %d | test_sex = 女\n", _id);
  16. else
  17. printf("test_id = %d | test_sex = 男\n", _id);
  18. _myrow = mysql_fetch_row(_myres);//循环读取
  19. }
  20. mysql_free_result(_myres);//释放缓存区数据 防止内存泄漏

修改

修改 LiShi 用户的 test_sex(性别) 为 男

  1. char _buf[] = "update test01 set test_sex=0 where test_name='LiShi'";
  2. //执行 sql 语句
  3. if (0 != mysql_real_query(&_mydata, _buf, sizeof(_buf)))
  4. {
  5. printf("mysql_real_query failed!\n");
  6. return 0;
  7. }

删除

删除 test_id(ID) 为 4 的数据

  1. char _buf[] = "delete from test01 where test_id='4'";
  2. //执行 sql 语句
  3. if (0 != mysql_real_query(&_mydata, _buf, sizeof(_buf)))
  4. {
  5. printf("mysql_real_query failed!\n");
  6. return 0;
  7. }

关闭mysql连接

mysql_close(&_mydata);//关闭 mysql 连接

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/663302
推荐阅读
相关标签
  

闽ICP备14008679号