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;
}
相关推荐
WangYaolove13141 小时前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
山岚的运维笔记1 小时前
SQL Server笔记 -- 第18章:Views
数据库·笔记·sql·microsoft·sqlserver
rainbow68892 小时前
EffectiveC++入门:四大习惯提升代码质量
c++
roman_日积跬步-终至千里2 小时前
【LangGraph4j】LangGraph4j 核心概念与图编排原理
java·服务器·数据库
汇智信科2 小时前
打破信息孤岛,重构企业效率:汇智信科企业信息系统一体化运营平台
数据库·重构
秋邱2 小时前
用 Python 写出 C++ 的性能?用CANN中PyPTO 算子开发硬核上手指南
开发语言·c++·python
我在人间贩卖青春3 小时前
C++之析构函数
c++·析构函数
野犬寒鸦3 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
霖霖总总3 小时前
[小技巧66]当自增主键耗尽:MySQL 主键溢出问题深度解析与雪花算法替代方案
mysql·算法
我在人间贩卖青春3 小时前
C++之数据类型的扩展
c++·字符串·数据类型