C++封装MySQL整体流程,并在Navicat展示

发布时间:2023年12月26日

将VS环境配置好。并且做小测试,具体可见上篇文章https://blog.csdn.net/wjl990316fddwjl/article/details/135185173?spm=1001.2014.3001.5501

C++封装MySQL

1、点击新建项目--空项目--项目名称;

2、右击头文件,添加类(这样就不用自己再去创建源文件了,你会发现源文件StudengManager.cpp也创建好了),点击确定

3、点击头文件--StudentManager.h进行编程

3.1、在后面所有代码文件里面,都加上这一句代码,防止报错

#define _CRT_SECURE_NO_WARNINGS

3.2、编写数据库连接的必须内容,将他放在class的私有数据里面(建议直接写MYSQL*con 后面在调用的时候就不用写&con了)

    MYSQL *con;
	const char* host = "127.0.0.1";
	const char* user = "root";
	const char* password = "*******";//数据库密码
	const char* database_name = "database_test";
	const int port = 3306;

3.3、首先写入构造函数和析构函数,在构造函数里面完成数据库的初始化以及连接,在析构函数里面完成数据库的关闭。具体代码如下:

#define _CRT_SECUER_NO_WARNINGS
#pragma once
class StudentManager
{
	StudentManager();
	~StudentManager();

};
//构造函数
StudentManager::StudentManager()
{
	con = mysql_init(NULL);
	mysql_library_init(0, NULL, NULL);
	//这两行代码必须在上面
	mysql_options(con, MYSQL_SET_CHARSET_NAME, "GBK");//必须有的,具体看我前几篇文章
	mysql_real_connect(con, host, user, password, database_name, port, NULL, 0);
}
//析构函数
StudentManager::~StudentManager()
{
	mysql_close(con);
	mysql_library_end();
}

这里说一个小技巧,右键构造函数或者析构函数,点击快速操作和重构—创建声明或定义,直接去StudentManager.cpp进行构造函数的扩充,这样就防止忘记了具体如何引用。

3.4、构建一个学生,将数据插入,当然也可以改成自己的;

typedef struct STUDENT 
{
	int Student_id;//学生id;
	string Student_name;//学生姓名
	string Class_id;//班级id
}Student;

3.5、到了构建函数的阶段啦---敲黑板? 我都写成bool类型的了

public:
	bool insert_Student(Student& stu);//增加数据
	bool delete_Student(int Student_id);//删除数据
	bool update_Student(Student& stu);//修改数据
	vector<Student>get_Student_all(string condition = "");//查找数据,将所有的数据都输出,用容器
	vector<Student>get_Student_Single(Student& stu, string Student_name);//查找数据,根据姓名查找单个数据
3.5.1、增加数据,数据库语句? ?c_str()必须有的 把string转换为字符串
INSERT into student(表名) values (学号,姓名,班级)
bool StudentManager::insert_Student(Student& stu)
{
	char sql[1024];

	sprintf(sql, "insert into student (student_id,student_name,class_id) values (%d,'%s','%s')",
		stu.Student_id, stu.Student_name.c_str(), stu.Class_id.c_str());
	//判断是否添加成功
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "添加失败:error:%s\n", mysql_error(con));
		return false;
	}
	return true;
}
3.5.2、删除数据 根据学生id删除
bool StudentManager::delete_Student(int Student_id)
{
	char sql[1024];

	sprintf(sql, "delete from student where student_id=%d\n", Student_id);

	if (mysql_query(con, sql))
	{
		fprintf(stderr, "删除失败:error:%s\n", mysql_error(con));
		return false;
	}

	return true;
}
3.5.3、修改数据? %s必须加单引号;? ****这里的student_id是主键,所以修改不了。如果修改的话,更改主键
bool StudentManager::update_Student(Student& stu)
{
	char sql[1024];

	sprintf(sql, "update student set student_name='%s',class_id='%s' where student_id=%d\n",
		stu.Student_name.c_str(), stu.Class_id.c_str(), stu.Student_id);

	if (mysql_query(con, sql))
	{
		fprintf(stderr, "更新失败:error:%s\n", mysql_error(con));
		return false;
	}

	return true;
}
3.5.4、查找数据(我写了两个,一个是将数据全部输出,一个是只输出id对应的数据)
vector<Student> StudentManager::get_Student_all(string condition)
{
	vector<Student>stulist;//创建stulist容器,待会将数据存放在里面

	char sql[1024];

	sprintf(sql, "select * from student %s\n",  condition.c_str());

	if (mysql_query(con, sql))
	{
		fprintf(stderr, "查找失败:error:%s\n", mysql_error(con));
		return {};//敲黑板  这里不可以是bool了,vector应该是{}
	}

	//获取查找到的数据

	MYSQL_RES* res = mysql_store_result(con);

	MYSQL_ROW row;

	while (row=mysql_fetch_row(res))
	{
		Student stu;
		//atoi将string转换为int
		stu.Student_id = atoi(row[0]);
		stu.Student_name = row[1];
		stu.Class_id = row[2];

		//将得到的数据存在stulist里面
		stulist.push_back(stu);
	}

	return stulist;
}
vector<Student> StudentManager::get_Student_Single(Student& stu, string Student_name)
{
	char sql[1024];
	vector<Student>stulist;
	sprintf(sql, "select * from student where student_name='%s'\n", stu.Student_name.c_str());
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "查找失败:error:%s\n", mysql_error(con));
		return {};
	}

	MYSQL_RES* res = mysql_store_result(con);
	MYSQL_ROW row;
	while (row=mysql_fetch_row(res))
	{
		Student stu;
		stu.Student_id = atoi(row[0]);
		stu.Student_name = row[1];
		stu.Class_id = row[2];
		stulist.push_back(stu);
	}

	return stulist;
}
3.5.5、测试,创建源文件test.cpp,将StudengManager.h导入

测试之前,设置单例模式,代码如下

public:
	//设置一个返回  单例模式
	static StudentManager* GetInstance()
	{
		//static静态变量全局只有一个,这样的话就不用创建多个连接了,只有一个连接就可以了
		static StudentManager StudentManager;
		return &StudentManager;
	}
a.测试增加
Student stu1 = { 444,"小王","测控一班" };
	StudentManager::GetInstance()->insert_Student(stu1);

打开Navicat,看到数据已经插入进去了

b.测试删除
    Student stu2;
	stu2.Student_id = 444;
	StudentManager::GetInstance()->delete_Student(stu2.Student_id);

打开Navicat,看到数据已经删除了

c.修改测试
	Student stu3 = { 333,"小樊","电器三班" };
	StudentManager::GetInstance()->update_Student(stu3);

打开Navicat,看到数据已经更新了

d.查找数据—查找所有数据
	vector<Student>ret= StudentManager::GetInstance()->get_Student_all();
    //容器遍历函数
	for (vector<Student>::iterator it = ret.begin();it != ret.end();it++)
	{
		cout << "学生ID :" << (*it).Student_id << "\n"
			<< "学生姓名:" << (*it).Student_name << "\n"
			<< "学生班级:" << (*it).Class_id << "\n"
			<< endl;
	}

运行

e、查找单个数据—根据姓名查找
    Student stu;
	stu.Student_name = "小樊";
	vector<Student>ret1 = StudentManager::GetInstance()->get_Student_Single(stu,     stu.Student_name);
	for (vector<Student>::iterator it = ret1.begin();it != ret1.end();it++)
	{
		cout << "学生ID :" << (*it).Student_id << "\n"
			<< "学生姓名:" << (*it).Student_name << "\n"
			<< "学生班级:" << (*it).Class_id << "\n"
			<< endl;
	}

运行

4、最终代码如下

4.1、StudentManager.h

#define _CRT_SECUER_NO_WARNINGS
#pragma once
#include<mysql.h>
#include<string>
#include<iostream>
#include<vector>
using namespace std;

typedef struct STUDENT 
{
	int Student_id;//学生id;
	string Student_name;//学生姓名
	string Class_id;//班级id
}Student;


class StudentManager
{
	StudentManager();
	~StudentManager();

public:
	bool insert_Student(Student& stu);//增加数据
	bool delete_Student(int Student_id);//删除数据
	bool update_Student(Student& stu);//修改数据
	vector<Student>get_Student_all(string condition = "");//查找数据,将所有的数据都输出,用容器
	vector<Student>get_Student_Single(Student& stu, string Student_name);//查找数据,根据姓名查找单个数据

public:
	//设置一个返回  单例模式
	static StudentManager* GetInstance()
	{
		//static静态变量全局只有一个,这样的话就不用创建多个连接了,只有一个连接就可以了
		static StudentManager StudentManager;
		return &StudentManager;
	}
private:
	MYSQL* con;
	const char* host = "127.0.0.1";
	const char* user = "root";
	const char* password = "990107Wjl@";
	const char* database_name = "database_test";
	const int port = 3306;
};

4.2、StudentManager.cpp

#define _CRT_SECURE_NO_WARNINGS

#include "StudentManager.h"

StudentManager::StudentManager()
{
	con = mysql_init(NULL);
	mysql_library_init(0, NULL, NULL);
	//这两行代码必须在上面
	mysql_options(con, MYSQL_SET_CHARSET_NAME, "GBK");//必须有的,具体看我前几篇文章
	mysql_real_connect(con, host, user, password, database_name, port, NULL, 0);
}

StudentManager::~StudentManager()
{
	mysql_close(con);
	mysql_library_end();
}

bool StudentManager::insert_Student(Student& stu)
{
	char sql[1024];

	sprintf(sql, "insert into student (student_id,student_name,class_id) values (%d,'%s','%s')",
		stu.Student_id, stu.Student_name.c_str(), stu.Class_id.c_str());
	//判断是否添加成功
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "添加失败:error:%s\n", mysql_error(con));
		return false;
	}
	return true;
}

bool StudentManager::delete_Student(int Student_id)
{
	char sql[1024];

	sprintf(sql, "delete from student where student_id=%d\n", Student_id);

	if (mysql_query(con, sql))
	{
		fprintf(stderr, "删除失败:error:%s\n", mysql_error(con));
		return false;
	}

	return true;
}

bool StudentManager::update_Student(Student& stu)
{
	char sql[1024];

	sprintf(sql, "update student set student_name='%s',class_id='%s' where student_id=%d\n",
		stu.Student_name.c_str(), stu.Class_id.c_str(), stu.Student_id);

	if (mysql_query(con, sql))
	{
		fprintf(stderr, "更新失败:error:%s\n", mysql_error(con));
		return false;
	}

	return true;
}

vector<Student> StudentManager::get_Student_all(string condition)
{
	vector<Student>stulist;//创建stulist容器,待会将数据存放在里面

	char sql[1024];

	sprintf(sql, "select * from student %s\n",  condition.c_str());

	if (mysql_query(con, sql))
	{
		fprintf(stderr, "查找失败:error:%s\n", mysql_error(con));
		return {};//敲黑板  这里不可以是bool了,vector应该是{}
	}

	//获取查找到的数据

	MYSQL_RES* res = mysql_store_result(con);

	MYSQL_ROW row;

	while (row=mysql_fetch_row(res))
	{
		Student stu;
		//atoi将string转换为int
		stu.Student_id = atoi(row[0]);
		stu.Student_name = row[1];
		stu.Class_id = row[2];

		//将得到的数据存在stulist里面
		stulist.push_back(stu);
	}

	return stulist;
}

vector<Student> StudentManager::get_Student_Single(Student& stu, string Student_name)
{
	char sql[1024];
	vector<Student>stulist;
	sprintf(sql, "select * from student where student_name='%s'\n", stu.Student_name.c_str());
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "查找失败:error:%s\n", mysql_error(con));
		return {};
	}

	MYSQL_RES* res = mysql_store_result(con);
	MYSQL_ROW row;
	while (row=mysql_fetch_row(res))
	{
		Student stu;
		stu.Student_id = atoi(row[0]);
		stu.Student_name = row[1];
		stu.Class_id = row[2];
		stulist.push_back(stu);
	}

	return stulist;
}

4.3、test.cpp

#define _CRT_SECURE_NO_WARNINGS
#include"StudentManager.h"

int main()
{
	/*Student stu1 = { 444,"小王","测控一班" };
	StudentManager::GetInstance()->insert_Student(stu1);*/

	/*Student stu2;
	stu2.Student_id = 444;
	StudentManager::GetInstance()->delete_Student(stu2.Student_id);*/

	/*Student stu3 = { 333,"小樊","电器三班" };
	StudentManager::GetInstance()->update_Student(stu3);*/

	/*vector<Student>ret= StudentManager::GetInstance()->get_Student_all();
	for (vector<Student>::iterator it = ret.begin();it != ret.end();it++)
	{
		cout << "学生ID :" << (*it).Student_id << "\n"
			<< "学生姓名:" << (*it).Student_name << "\n"
			<< "学生班级:" << (*it).Class_id << "\n"
			<< endl;
	}*/

	Student stu;
	stu.Student_name = "小樊";
	vector<Student>ret1 = StudentManager::GetInstance()->get_Student_Single(stu, stu.Student_name);
	for (vector<Student>::iterator it = ret1.begin();it != ret1.end();it++)
	{
		cout << "学生ID :" << (*it).Student_id << "\n"
			<< "学生姓名:" << (*it).Student_name << "\n"
			<< "学生班级:" << (*it).Class_id << "\n"
			<< endl;
	}

	system("pause");
	return 0;
}

5、撒花,完结

文章来源:https://blog.csdn.net/wjl990316fddwjl/article/details/135200763
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。