C++操作Mysql数据库/Linux下
本文链接: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下的更多相关文章
- python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy
内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...
- PHP操作MySQL数据库之天龙八部 -- 七贱下天山 -- 六脉神剑
天龙八部 八步操作数据库 七贱下天山 七步操作数据库 (将判断错误省略) 六脉神剑 六步操作数据库(将判断错误省略,将选择数据库添加到第一步 ...
- Windows下安装MySQLdb, Python操作MySQL数据库的增删改查
这里的前提是windows上已经安装了MySQL数据库,且配置完成,能正常建表能操作. 在此基础上仅仅需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了.仅仅有1M ...
- Go语言操作MySQL数据库
Go语言操作MySQL数据库 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用 ...
- python操作mysql数据库的常用方法使用详解
python操作mysql数据库 1.环境准备: Linux 安装mysql: apt-get install mysql-server 安装python-mysql模块:apt-get instal ...
- 通过mysqlclient操作MySQL数据库
一,安装mysql 如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可. Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的l ...
- ASP.NET Core使用EF Core操作MySql数据库
ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...
- 【转】python操作mysql数据库
python操作mysql数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库 ...
- python接口自动化(三十八)-python操作mysql数据库(详解)
简介 现在的招聘要求对QA人员的要求越来越高,测试的一些基础知识就不必说了,来说测试知识以外的,会不会一门或者多门开发与语言,能不能读懂代码,会不会Linux,会不会搭建测试系统,会不会常用的数据库, ...
随机推荐
- 1、uiautomator2常用语法
uiautomator2常用语法 连接设备 使用USB连接: d=u2.connect_USB('148b4090')输入手机序列号 d是给当前连接设备定位一个变量 获取设备的信息: print(d. ...
- Java--8--新特性--新的日期API
LocalDate.LocalTime.LocalDateTime 类的实 例是不可变的对象,分别表示使用 ISO-8601日 历系统的日期.时间.日期和时间. Instant 时间戳, 用于“时间戳 ...
- 【转】TCP性能优化之避免慢启动
TCP协议中有个慢启动,在<TCP/IP详解卷一>中占据的篇幅很小,但是这个东西,在某些业务场景下,对性能的影响非常大. 什么是慢启动 最初的TCP的实现方式是,在连接建立成功后便会向网络 ...
- 铁力项目mysql异常处理过程记录
地区:铁力 故障:2019-06-26 10:19:34 139921514837760 [ERROR] mysqld: Error writing file 'mysql-bin' (errno: ...
- DFS遍历拷贝所有子文件夹及目录列表 (Java版)
如题 注意,文件夹是不能拷贝的, 需要mkdir的 文件选择合适的流进行拷贝 main测试方法 /** * 主测试类,默认将D:\\base01 下的复制到D:\\base02 * @param ar ...
- Redis与Python的交互
驱动模块 redis模块用来在Python环境下驱动Redis数据库 可以直接用pip方式安装 pip install redis 或者国内镜像下载: pip install -i https://p ...
- 《hello-world》第九次团队作业:Beta冲刺与验收准备
项目 内容 这个作业属于哪个课程 2016级计算机科学与工程学院软件工程(西北师范大学) 这个作业的要求在哪里 实验十三 团队作业9:Beta冲刺与团队项目验收 团队名称 <hello--wor ...
- LG4762 Virus synthesis
Virus synthesis 初始有一个空串,利用下面的操作构造给定串 S . 串开头或末尾加一个字符 串开头或末尾加一个该串的逆串 求最小化操作数, ∣S∣≤105 . 题解 显然应该多使用操作2 ...
- wait,waitpid学习测试
用man wait学习wait waitpid的使用 wait()函数功能:wait()函数使父进程暂停执行,直到它的一个子进程结束为止,该函数的返回值是终止运行的子进程的PID. 参数status所 ...
- matlab的poly()函数
MATLAB中的poly()函数是用于求以向量为解的方程或方阵的特征多项式,可以直接传递多项式方程的系数矩阵. 1.poly([1 2 3])使用的举例. P=poly([1 2 3]) 可以解出P= ...