本文链接:https://blog.csdn.net/Tanswer_/article/details/72796570
想用C++写项目,数据库是必须的,所以这两天学了一下C++操作Mysql数据库的方法。也没有什么教程,就是在网上搜的知识,下面汇总一下。
连接MySQL数据库有两种方法:第一种是使用ADO连接,不过这种只适合Windows平台;第二种是使用MySQL自己的C API函数连接数据库。我是在Linux平台下开发,所以就采用第二种方法,有很多Api函数,但是常用的就几个,我也是就用到其中的几个。

API函数
1.mysql_real_connect()
连接一个mysql服务器

MYSQL *mysql_real_connect (MYSQL *mysql,
const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long client_flag)

如果连接成功,返回MYSQL*连接句柄。如果连接失败,返回NULL。对于成功的连接,返回值与第1个参数的值相同

2.mysql_query()
执行指定”以NULL终结的字符串”的SQL查询

返回一个结果表,假定查询成功,可以调用 mysql_num_rows() 来查看对应于 SELECT 语句返回了多少行,或者调用 mysql_affected_rows() 来查看对应于 DELETE,INSERT,REPLACE 或 UPDATE 语句影响到了多少行。

3.mysql_store_result()
MYSQL_RES *mysql_store_result(MYSQL *mysql)

检索完整的结果集至客户端。客户端处理结果集最常用的方式是通过调用mysql_store_result(),一次性地检索整个结果集。该函数能从服务器获得查询返回的所有行,并将它们保存在客户端。对于成功检索了数据的每个查询(SELECT、SHOW、DESCRIBE、EXPLAIN、CHECK TABLE等),必须调用mysql_store_result()或mysql_use_result() 。对于其他查询,不需要调用mysql_store_result()或mysql_use_result(),但是如果在任何情况下均调用了mysql_store_result(),它也不会导致任何伤害或性能降低。

4.mysql_num_rows()
返回结果集中的行数。

5.mysql_num_fields()
返回结果集中的字段数,如果失败,则返回 false。

6.mysql_fetch_field()
MYSQL_FIELD* mysql_fetch_field(MYSQL_RES *result);
获取下一个表字段的类型,结束返回NULL。

7.mysql_fetch_row()
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);
从结果集中获取下一行,成功返回一个数组,值大于0。

8.mysql_fetch_field_direct()
MYSQL_FIELD* mysql_fetch_field_direct(MYSQL_RES *result, int i);
给定字段编号,返回表字段的类型,结束返回NULL。

简单的学生信息管理代码
光看也记不住啊,就用这些函数写了一个学生信息管理界面,唉,去年这时候C语言课程设计,当时还不知道用数据库,全用文件写的,知道晚了很后悔啊。。。。下面是代码:

1 /*************************************************************************
2 > File Name: student.cpp
3 > Author: Tanswer_
4 > Mail: 98duxm@gmail.com
5 > Created Time: 2017年05月28日 星期日 16时50分34秒
6 ************************************************************************/
7
8 #include <iostream>
9 #include <string>
10 #include <stack>
11 #include <algorithm>
12 #include <sstream>
13 #include <mysql/mysql.h>
14 #include <unistd.h>
15
16 using namespace std;
17
18
19 MYSQL mysql;
20 MYSQL_ROW row;
21 MYSQL_FIELD* field = NULL;
22 MYSQL_RES* result;
23
24 string IntToStr(int num)
25 {
26 stringstream ss;
27 ss.clear();
28 ss << num;
29 return ss.str();
30 }
31
32 void Add()
33 {
34 string fname,fsex,ftel,faddr;
35 int fage;
36 char choice;
37 do
38 {
39 ┊ cout << "请依次输入以下信息:" << endl;
40 ┊ cout << "\nName: ";cin >> fname;
41 ┊ cout << "\nSex: ";cin >> fsex;
42 ┊ cout << "\nAge: "; cin >> fage;
43 ┊ cout << "\nTel: "; cin >> ftel;
44 ┊ cout << "\nAddr: "; cin >> faddr;
45
46 ┊ string sql = "INSERT INTO Infor (name,sex,tel,addr,age) values('"+fname+"','"+fsex+"','"+ftel+"','"+faddr+"', "+IntToStr(fage)+");";
47 ┊ //string sql = "INSERT INTO Infor (name,sex,age,tel,addr) values('小红','女',18,'13333333333', '陕西省西安市雁塔区');";
48
49 ┊ mysql_query(&mysql,sql.c_str());
50 ┊ ┊
51 ┊ cout << "是否继续添加(y/n)?: ";
52 ┊ cin >> choice;
53 }while(choice == 'y');
54
55 }
56
57 void Select()
58 {
59 int id;
60 cout << "请输入要查询学生的学号: ";
61 cin >> id;
62
63 string sql = "SELECT * FROM Infor WHERE id = "+IntToStr(id)+";";
64 mysql_query(&mysql,sql.c_str());
65
66 result = mysql_store_result(&mysql);
67 if(result == NULL)
68 ┊ cout << "fail\n";
69
70 for(int i=0; i<mysql_num_fields(result); i++)
71 {
72 ┊ field = mysql_fetch_field_direct(result,i);
73 ┊ cout << field->name << "\t\t";
74 }
75 cout << endl;
76
77 row = mysql_fetch_row(result);
78 while(row != NULL)
79 {
80 ┊ for(int i=0; i<mysql_num_fields(result); i++)
81 ┊ {
82 ┊ ┊ cout << row[i] << "\t\t";
83 ┊ }
84 ┊ cout << endl;
85 ┊ row = mysql_fetch_row(result);
86 }
87 }
88
89
90 void Update()
91 {
92 int id;
93 char choice;
94 string newaddr;
95 ┊ cout << "请输入要修改同学的学号: ";
96 ┊ cin >> id;
97 ┊ cout << endl << "请输入修改后的地址: ";
98 ┊ cin >> newaddr;
99 ┊ string sql = "UPDATE Infor SET addr = '"+newaddr+"'WHERE id= "+IntToStr(id)+"; ";
100 ┊ mysql_query(&mysql,sql.c_str());
101 ┊
102 }
103
104
105 int main()
106 {
107 char choice[5];
108
109 mysql_init(&mysql);
110 /*连接数据库*/
111 if(!mysql_real_connect(&mysql,"localhost","root","dxm242012","Student",0,NULL,0))
112 {
113 ┊ cout << "connect fial\n";
114 ┊ return -1;
115 }
116
117 while(atoi(choice) != 'q')
118 {
119 ┊ sleep(4);
120 ┊ system("clear");
121 ┊ cout << "1.添加学生信息" << endl;
122 ┊ cout << "2.查询学生信息" << endl;
123 ┊ cout << "3.修改学生信息" << endl;
124
125 ┊ cin >> choice;
126
127 ┊ cout << choice << endl;
128 ┊ switch(atoi(choice))
129 ┊ {
130 ┊ ┊ case 1:
131 ┊ ┊ ┊ Add();
132 ┊ ┊ ┊ break;
133 ┊ ┊ case 2:
134 ┊ ┊ ┊ Select();
135 ┊ ┊ ┊ break;
136 ┊ ┊ case 3:
137 ┊ ┊ ┊ Update();
138 ┊ ┊ ┊ break;
139 ┊ ┊ default:
140 ┊ ┊ ┊ break;
141 ┊ }
142 }
143
144 mysql_close(&mysql);
145 return 0;
146 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
C++封装MyDB类
后来又把这些函数简单的封装了一下,方便以后直接用。

1 /*************************************************************************
2 > File Name: myDB.h
3 > Author: Tanswer_
4 > Mail: 98duxm@gmail.com
5 > Created Time: 2017年05月28日 星期日 22时26分22秒
6 ************************************************************************/
7
8 #ifndef _MYDB_H
9 #define _MYDB_H
10
11 #include <string>
12 #include <iostream>
13 #include <mysql/mysql.h>
14 using namespace std;
15
16 class MyDB
17 {
18
19 public:
20 MyDB();
21 ~MyDB();
22 bool InitDB(string host,string user,string pwd,string dbname);
23 bool ExeSQL(string sql);
24 private:
25 MYSQL* mysql;
25 MYSQL* mysql;
26 MYSQL_ROW row;
27 MYSQL_RES* result;
28 MYSQL_FIELD* field;
29 };
30
31
32 #endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
1 /*************************************************************************
2 > File Name: myDB.cpp
3 > Author: Tanswer_
4 > Mail: 98duxm@gmail.com
5 > Created Time: 2017年05月28日 星期日 22时27分18秒
6 ************************************************************************/
7
8 #include <iostream>
9 #include <string>
10 #include <stack>
11 #include <algorithm>
12 #include <mysql/mysql.h>
13 #include "myDB.h"
14
15 using namespace std;
16
17 MyDB::MyDB()
18 {
19 mysql = mysql_init(NULL);
20 if(mysql == NULL)
21 {
22 ┊ cout << "Error: " << mysql_error(mysql);
23 ┊ exit(-1);
24 }
25 }
26
27 MyDB::~MyDB()
28 {
29 if(!mysql)
30 {
31 ┊ mysql_close(mysql);
32 }
33 }
34
35 bool MyDB::InitDB(string host,string user,string pwd,string dbname)
36 {
37 /*连接数据库*/
38 if(!mysql_real_connect(mysql,host.c_str(),user.c_str(),pwd.c_str(),dbname.c_str(),0,NULL,0))
39 {
40 ┊ cout << "connect fial: " << mysql_error(mysql);
41 ┊ exit(-1);
42 }
43 return true;
44 }
45
46 bool MyDB::ExeSQL(string sql)
47 {
48 /*执行失败*/
49 if(mysql_query(mysql,sql.c_str()))
50 {
51 ┊ cout << "query fail: " << mysql_error(mysql);
52 ┊ exit(1);
53 }
54
55 else
56 {
57 ┊ /*获取结果集*/
58 ┊ result = mysql_store_result(mysql);
59
60 ┊ int fieldnum = mysql_num_fields(result);
61 ┊ for(int i=0; i<fieldnum; i++)
62 ┊ {
63 ┊ ┊ row = mysql_fetch_row(result);
64 ┊ ┊ if(row <= 0)
65 ┊ ┊ ┊ break;
66 ┊ ┊ for(int j=0; j<fieldnum; j++)
67 ┊ ┊ {
68 ┊ ┊ ┊ cout << row[j] << "\t\t";
69 ┊ ┊ }
70 ┊ ┊ cout << endl;
71 ┊ }
72 ┊ mysql_free_result(result);
73 }
74 return true;
75 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
1 /*************************************************************************
2 > File Name: main.cpp
3 > Author: Tanswer_
4 > Mail: 98duxm@gmail.com
5 > Created Time: 2017年05月28日 星期日 22时53分43秒
6 ************************************************************************/
7
8 #include <iostream>
9 #include <string>
10 #include <stack>
11 #include <algorithm>
12 #include <mysql/mysql.h>
13 #include "myDB.h"
14
15 using namespace std;
16
17
18 int main()
19 {
20 MyDB db;
21 db.InitDB("localhost","root","xxxxxx","Student");
22 db.ExeSQL("SELECT * FROM Infor;");
23 return 0;
24 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
以下是运行结果:

下面是遇到的问题:
1. 编译时出错
没有那个文件或目录
#include<mysql/mysql.h>
^
编译中断。
解决:除了mysql-client和mysql-server,又安装了mysql-devel,然后就解决了。
2. 自定义的变量传入sql语句时,出现问题
在网上查找到这样一种格式,
string sql = "INSERT INTO Infor (name,sex,tel,addr,age) values('"+fname+"','"+fsex+"','"+ftel+"','"+faddr+"', "+IntToStr(fage)+");";
然后string类型的可以成功,整型的变量还是不行,我又写了个函数把int转为string。

string IntToStr(int num)
{
stringstream ss;
ss.clear();
ss << num;
return ss.str();
}

原文链接:https://blog.csdn.net/tanswer_/article/details/72796570

最新文章

  1. 禁用 baloo_file_extractor 加速 ubuntu 14.04 (KDE)
  2. MySQL sharding的几个参考地址
  3. tabbar底部标题和子控制器标题为什么会保持一致?
  4. 无线客户端框架设计(5):调用MobileAPI的设计(iOS篇)
  5. 获取客户端ip并用正则表达式验证
  6. 转载:LBP代码详细注释
  7. git基础入门之常用命令操作
  8. AppStore 审核中文版 --- 程序员必看
  9. QImage与QPixmap加载图片效果(QImage不能拉伸图片,QPixmap默认拉伸图片)
  10. 机器学习公开课~~~~mooc
  11. Change the ball(找规律)
  12. ui主线程控件的更新就让这个activity的异步任务做完整
  13. IdentityServer4 实现 OAuth 2.0(密码模式 - HTTP Post 方式)
  14. 51ak带你看MYSQL5.7源码1:main入口函数
  15. bgfx入门练习1——切换图形API驱动模式DX与OpenGL
  16. [No000010A]Git3/9-创建版本库
  17. iOS APP 在前台时弹出本地通知
  18. Reloading Java Classes 301: Classloaders in Web Development — Tomcat, GlassFish, OSGi, Tapestry 5 and so on Translation
  19. HTML5学习笔记(十一):JavaScript基础
  20. EF code First数据迁移学习笔记

热门文章

  1. java对象json序列化时忽略值为null的属性
  2. Django图书管理系统(前端对有外键的数据表增删改查)
  3. 《The One!团队》第八次团队作业:Alpha冲刺
  4. Keras神经网络data generators解决数据内存
  5. sleep() 和 wait() 区别是什么?
  6. Java 通过HttpClient Post方式提交json请求
  7. LightOJ - 1170 - Counting Perfect BST(卡特兰数)
  8. LeetCode 364. Nested List Weight Sum II
  9. 阿里开源线上应用调试利器 Arthas的背后
  10. 洛谷 P1190 接水问题 题解