C++ implements the database's addition, deletion, modification and query function demo

Preface

I recently interned in a company and was given two small demos to complete on the day I joined. The first one was to use C++ to implement the http protocol exposure of the web front-end, and the other was to use C++ to implement the database connection and the corresponding add, delete, modify and check functions. Talk more and code.

1.Preparation conditions

1.1Create data table

The User table structure is as follows:

type of data Field explain
int id serial number
string username username
int password password
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(18) NOT NULL,
  `password` int(18) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

1.2 Configuration items

1. Open the project properties
Insert image description here
2. Edit the include directory and turn off sdl check
3. Add the include directory path of Mysql, click OK, and apply
Insert image description here

2. Connect to the database

2.1 Create UserManager.h file

Used to define and declare some constants and methods. Each piece of code has comments, as follows

#pragma once //防止头文件多次加载
#include <mysql.h>//用于数据库连接
#include <iostream>//用于读写数据流
#include <string>//字符串
#include<vector>//vector容器

using namespace std;//标准命名空间

typedef struct User {
	int id;
	string username;
	int password;
}User;//映射数据表User的结构
class UserManager
{
	UserManager();//构造函数,用于创建实例化后的对象,默认调用
	~UserManager();//析构函数,用来销毁该实例化后的对象,由系统调用
public:
	static UserManager* GetInstance() { //单例模式
		static UserManager UserManager;
		return &UserManager;
	}
public: //定义增删改查的函数声明,其中&为引用符号,传入的是该对象的地址,便于直接操作该对象
	bool insert_user(User& user);
	bool delete_user(User& user);
	bool update_user(User& user);
	vector<User> query_user(string condition = "");
private://定义一些常量
	MYSQL* con;
	const char* host = "127.0.0.1";//主机IP地址
	const char* user = "root";//用户名
	const char* pw = "123456";//密码
	const char* database_name = "test";//数据库名称
	const int port = 3306;//端口号
};

2.2 Create UserManager.cpp file

#include "UserManager.h" //引入头文件
using namespace std;//标准命名空间

//实现头文件中声明的构造函数
UserManager::UserManager() {
	con = mysql_init(NULL);//初始化连接
	//设置字符编码
	mysql_options(con, MYSQL_SET_CHARSET_NAME, "GBK");
	//连接数据库
	if (!mysql_real_connect(con, host, user, pw, database_name, port, NULL, 0))
	{
		std::cout << "Failed to connect with database";
		exit(1);
	}
}
//实现头文件中声明的析构函数
UserManager::~UserManager() {
	mysql_close(con);
}
//增加用户
bool  UserManager::insert_user(User& user)
{
	char sql[8192];//声明字符数组
	sprintf_s(sql, "insert into user(id,username,password) values (%d,'%s',%d)", user.id, user.username.data(), user.password);//sql语句
	if (mysql_query(con, sql))//执行sql语句
	{
		fprintf(stderr, "Failed to insert data,Error:%s\n", mysql_error(con));
		return false;
	}
	return true;
}
//删除用户
bool UserManager::delete_user(User& user)
{
	char sql[8192];
	sprintf_s(sql, "	DELETE FROM  user WHERE id=%d", user.id);
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to delete data,Error:%s\n", mysql_error(con));
		return false;
	}
	return true;
}
//修改用户
bool UserManager::update_user(User& user)
{
	char sql[8192];
	sprintf_s(sql, "	UPDATE user SET  username='%s',password=%d WHERE id=%d",
		user.username.data(), user.password,user.id);
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to updata data,Error:%s\n", mysql_error(con));
		return false;
	}
	return true;

}
//查询用户
vector<User> UserManager::query_user(string condition)
{
	vector<User> userList;
	char sql[8192];
	sprintf(sql, "	SELECT * FROM user %s",condition.c_str());
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to select data,Error:%s\n", mysql_error(con));
		return {};
	}
	MYSQL_RES* res = mysql_store_result(con);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(res)))
	{
		User user;
		user.id = atoi(row[0]);
		user.username = atoi(row[1]);
		user.password = atoi(row[2]);
		userList.push_back(user);
	}
	for (int i = 0; i < userList.size(); i++)
	{
		cout << userList[i].id << "," << userList[i].username << "," << userList[i].password << endl;
	}
	return userList;
}

3. Run the code

Create a main.cpp file and the test code is as follows

#include <mysql.h>
#include <iostream>
#include "UserManager.h"
using namespace std;

int main() {
	//User的插入
	User user1{1,"测试",123};//实例化一个User对象
	UserManager::GetInstance()->insert_user(user1);//调用插入方法
}

4.Source code

Click here to get

Guess you like

Origin blog.csdn.net/qq_52431815/article/details/131696970