C/C++数据库编程

文章目录

  • [0. Mysql安装与开发环境配置](#0. Mysql安装与开发环境配置)
  • [1. win10 Navicat 连接虚拟机的MySQL需要关闭防火墙](#1. win10 Navicat 连接虚拟机的MySQL需要关闭防火墙)
  • [2. 由于找不到libmysql.dIl, 无法继续执行代码。重新安装程序可能会解决此问题。](#2. 由于找不到libmysql.dIl, 无法继续执行代码。重新安装程序可能会解决此问题。)
  • [3. 测试连接数据库,并插入数据](#3. 测试连接数据库,并插入数据)
  • [4. C++封装MySQL增删改查操作](#4. C++封装MySQL增删改查操作)

0. Mysql安装与开发环境配置

MySQL安装_win10(超详细)

C/C++访问MySQL数据库

1. win10 Navicat 连接虚拟机的MySQL需要关闭防火墙

  1. 查看防火墙端口开放的情况:
lua 复制代码
service firewalld status
  1. 关闭防火墙:
vbscript 复制代码
systemctl stop firewalld

2. 由于找不到libmysql.dIl, 无法继续执行代码。重新安装程序可能会解决此问题。

D:\MySQL\mysql-8.0.33-winx64\lib目录下的libmysql.dll拷贝到E:\Code\VS2022\student_manager\student_manager

3. 测试连接数据库,并插入数据

cpp 复制代码
#include <iostream>
#include <mysql.h>
#include <string>

using namespace std;

const char* host = "127.0.0.1";
const char* user = "root";
const char* pw = "111111";
const char* database_name = "student_manager";
const int port = 3306;

typedef struct Student {
	int student_id;
	string student_name;
	string class_id;
}Student;

int main() {
	MYSQL* 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)) {
		fprintf(stderr, "Failed to connect to database : Error:%s\n", mysql_errno(con));
		return -1;
	}

	Student stu = { 1001, "吴彦祖", "计算机2班" };

	char sql[256];
	sprintf_s(sql, "insert into students(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, "Failed to insert data : Error:%s\n", mysql_errno(con));
		return -1;
	}

	mysql_close(con);

	return 0;
}

4. C++封装MySQL增删改查操作

cpp 复制代码
// StudentManager.h
#ifndef STUDENTMANAGER_H
#define STUDENTMANAGER_H

#include <mysql.h>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

typedef struct Student {
    int student_id;
    string student_name;
    string class_id;
}Student;

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

public: // 单例模式:只创建一个实体,即只创建一个学生管理类即可
    static StudentManager* GetInstance() {
        static StudentManager StudentManager;
        return &StudentManager;
    }

public:
    bool insert_student(Student& stu);
    bool update_student(Student& stu);
    bool delete_student(int student_id);
    vector<Student> get_students(string condition = "");

private:
    MYSQL* con;
    const char* host = "127.0.0.1";
    const char* user = "root";
    const char* pw = "111111";
    const char* database_name = "student_manager";
    const int port = 3306;
};

#endif // STUDENTMANAGER_H
cpp 复制代码
// StudentManager.cpp
#include "StudentManager.h"

StudentManager::StudentManager() {
	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)) {
		fprintf(stderr, "Failed to connect to database : Error:%s\n", mysql_errno(con));
		exit(1);
	}
}

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

bool StudentManager::insert_student(Student& stu) {
	char sql[256];
	sprintf_s(sql, "INSERT INTO students(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, "Failed to insert data : Error:%s\n", mysql_errno(con));
		return false;
	}

	return true;
}

bool StudentManager::update_student(Student& stu) {
	char sql[256];
	sprintf_s(sql, "UPDATE students SET student_name = '%s', class_id = '%s' WHERE student_id = %d", 
			stu.student_name.c_str(), stu.class_id.c_str(), stu.student_id);

	if (mysql_query(con, sql)) {
		fprintf(stderr, "Failed to update data : Error:%s\n", mysql_errno(con));
		return false;
	}

	return true;
}

bool StudentManager::delete_student(int student_id) {
	char sql[256];
	sprintf_s(sql, "DELETE FROM students WHERE student_id = %d", student_id);

	if (mysql_query(con, sql)) {
		fprintf(stderr, "Failed to delete data : Error:%s\n", mysql_errno(con));
		return false;
	}

	return true;
}

vector<Student> StudentManager::get_students(string condition) {
	vector<Student> stuList;

	char sql[256];
	sprintf_s(sql, "SELECT * FROM students %s", condition.c_str());

	if (mysql_query(con, sql)) {
		fprintf(stderr, "Failed to select data : Error:%s\n", mysql_errno(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.emplace_back(stu);
	}
	return stuList;
}
cpp 复制代码
// main.cpp
#include "StudentManager.h"

int main() {
    Student stu{999, "彭于晏", "网工1班"};
    StudentManager::GetInstance()->insert_student(stu);

    Student stu{999, "彭于晏", "网工3班" };
    StudentManager::GetInstance()->update_student(stu);

    StudentManager::GetInstance()->delete_student(1000);

    vector<Student> ret = StudentManager::GetInstance()->get_students();
    for (auto& t : ret) {
        cout << t.student_id << " " << t.student_name << " " << t.class_id << endl;
    }

    return 0;
}

// main.cpp
#include "StudentManager.h"

int main() {
    StudentManager* studentManager = StudentManager::GetInstance();
    Student stu1{1009, "彭于晏", "网工1班"};
    studentManager->insert_student(stu1);

    Student stu2{999, "胡歌", "网工3班" };
    studentManager->update_student(stu2);

    studentManager->delete_student(1001);

    vector<Student> ret = studentManager->get_students();
    for (auto& t : ret) {
        cout << t.student_id << " " << t.student_name << " " << t.class_id << endl;
    }

    return 0;
}
相关推荐
A懿轩A10 分钟前
C/C++ 数据结构与算法【树和二叉树】 树和二叉树,二叉树先中后序遍历详细解析【日常学习,考研必备】带图+详细代码
c语言·数据结构·c++·学习·二叉树·
不剪发的Tony老师10 分钟前
SQL实现新年倒计时功能
数据库·sql
小小药17 分钟前
009-spring-bean的实例化流程
java·数据库·spring
hjxxlsx21 分钟前
探索 C++ 自定义函数的深度与广度
开发语言·c++
DashVector40 分钟前
如何通过HTTP API插入或更新Doc
大数据·数据库·数据仓库·人工智能·http·数据库架构·向量检索
hac132244 分钟前
瀚高数据库
数据库
小小小妮子~1 小时前
深入理解 MySQL 架构
数据库·mysql·架构
lijiachang0307182 小时前
设计模式(一):单例模式
c++·笔记·学习·程序人生·单例模式·设计模式·大学生
man20172 小时前
【2024最新】基于Python+Mysql+django的水果销售系统Lw+PPT
数据库·mysql·django
<但凡.2 小时前
题海拾贝:蓝桥杯 2020 省AB 乘法表
c++·算法·蓝桥杯