本文链接: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

C++操作Mysql数据库/Linux下的更多相关文章

  1. python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy

    内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...

  2. PHP操作MySQL数据库之天龙八部 -- 七贱下天山 -- 六脉神剑

    天龙八部            八步操作数据库 七贱下天山        七步操作数据库  (将判断错误省略) 六脉神剑            六步操作数据库(将判断错误省略,将选择数据库添加到第一步 ...

  3. Windows下安装MySQLdb, Python操作MySQL数据库的增删改查

    这里的前提是windows上已经安装了MySQL数据库,且配置完成,能正常建表能操作. 在此基础上仅仅需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了.仅仅有1M ...

  4. Go语言操作MySQL数据库

    Go语言操作MySQL数据库 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用 ...

  5. python操作mysql数据库的常用方法使用详解

    python操作mysql数据库 1.环境准备: Linux 安装mysql: apt-get install mysql-server 安装python-mysql模块:apt-get instal ...

  6. 通过mysqlclient操作MySQL数据库

    一,安装mysql 如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可. Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的l ...

  7. ASP.NET Core使用EF Core操作MySql数据库

    ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...

  8. 【转】python操作mysql数据库

    python操作mysql数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库 ...

  9. python接口自动化(三十八)-python操作mysql数据库(详解)

    简介 现在的招聘要求对QA人员的要求越来越高,测试的一些基础知识就不必说了,来说测试知识以外的,会不会一门或者多门开发与语言,能不能读懂代码,会不会Linux,会不会搭建测试系统,会不会常用的数据库, ...

随机推荐

  1. git修改提交历史中的author信息

    当次提交 当次的提交显示指定提交者信息: git commit -m "Initial commit" --author="mn <mn@furzoom.com&g ...

  2. 当安装、卸载件包时,出现依赖问题 error: Failed dependencies

    error: Failed dependencies:…… 依赖关系非常复杂,当你试图先安装任何一个包时都会出现这样的依赖关系错误,这时候你就应该强制安装了,我认为只要你把服务或软件需要的包都装上,强 ...

  3. vscode 上安装 leetcode插件

    vscode 真是一款非常好的轻量级的代码编辑工具,无论windows还是ubuntu使用体验都非常好. leetcode用来练练脑子吧,不要老年痴呆了. 1. 安装vscode Ubuntu先去下载 ...

  4. Maven02 -学习总结&学习文档 -踩坑123

    maven在开发中的作用 ①自动添加第三方 jar 包 在今天的 JavaEE 开发领域,有大量的第三方框架和工具可以供我们使用.要使用这些 jar 包最简单的方法就是复制粘贴到 WEB-INF/li ...

  5. java中List集合

    List集合是一个元素有序可以重复的集合,集合中每个元素都有其对应的顺序索引.List集合允许使用重复集合,前面博客写到Set不允许有重复集合.List集合可以通过索引来访问指定位置的集合元素. Li ...

  6. 大马过安全狗拿webshell方法

    很多拿站的朋友,都知道大马很多都会被安全狗拦截,最近一个大牛给我一个方法,竟然成功,所以分享下这个方法. 将大马写到一个txt文件里面,命名为dama.txt,再建一个文本文档,asp的就写入:< ...

  7. 基于Python3+Requests的贴吧签到助手

    因为总是忘记签到,所以尝试写了一个签到脚本,因为使用的是Python3,所以没法使用Urllib2,于是选择了Requests,事实证明,Requests比Urllib2好用.整体思路比较简单,就是模 ...

  8. JS基础_自增和自减

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. Poj 2018 Best Cow Fences(分数规划+DP&&斜率优化)

    Best Cow Fences Time Limit: 1000MS Memory Limit: 30000K Description Farmer John's farm consists of a ...

  10. 14、master原理与源码分析

    一.主备切换机制原理剖析 1.图解 2.部分源码 ###master.scala中的completeRecovery方法: /* * 完成Master的主备切换 */ def completeReco ...