C/C++ MySQL增删改查

测试MySQL连接

参考上一节 🎯C/C++连接MySQL

在配置好之后,测试MySQL是否正常连接

#include <iostream>
#include <string>
#include <mysql.h>
using namespace std;
const char* host = "127.0.0.1";
const char* user = "root";
const char* pw = "123456";
const char* database_name = "sm";
const int port = 3306;


struct Student
{
	int SNo;
	string CLno;
	string SName;
	int SSex;
	string SDate;
};
int main2()
{
	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_error(con));
		return -1;
	}
	Student stu{ 20059, "020102", "李明", 1, "2000-04-09"};
	char sql[1024];
	sprintf(sql, "insert into student (SNo, CLno, SName, SSex, SDate) value(%d,'%s','%s',%d,'%s')", stu.SNo, stu.CLno.c_str(), stu.SName.c_str(), stu.SSex, stu.SDate.c_str());
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to insert data: Error: %s\n", mysql_error(con));
		return -1;
	}
	cout << "insert sucessful\n";
	mysql_close(con);
	return 0;
}	

数据库-学生表

在MySQL中建库建表,表结构如下:
在这里插入图片描述

StudentManager.h

#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <mysql.h>
using namespace std;
struct Student
{
	int SNo;
	string CLno;
	string SName;
	int SSex;
	string SDate;
};

class StudentManager
{
public:
	StudentManager();
	~StudentManager();
public:
	//单例模式
	static StudentManager* GetInstance()
	{
		static StudentManager StudentManager;
		return &StudentManager;
	}

public:
	bool insert_student(Student& t);
	bool delete_student(Student& t);
	bool update_student(Student& t);
	vector<Student> get_student(string condition="");

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

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_error(con));
		exit(1);
	}
}

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

bool StudentManager::insert_student(Student& stu)
{
	char sql[1024];
	sprintf(sql, "insert into student (SNo, CLno, SName, SSex, SDate) value(%d,'%s','%s',%d,'%s')", stu.SNo, stu.CLno.c_str(), stu.SName.c_str(), stu.SSex, stu.SDate.c_str());
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to insert data: Error: %s\n", mysql_error(con));
		return false;
	}
	cout << "insert sucessful\n";
	return true;
}

bool StudentManager::delete_student(Student& stu)
{
	char sql[1024];
	sprintf(sql, "delete from student where SNo=%d", stu.SNo);
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to delete data: Error: %s\n", mysql_error(con));
		return false;
	}
	cout << "delete sucessful\n";
	return true;
}

bool StudentManager::update_student(Student& stu)
{
	char sql[1024];
	sprintf(sql, "update student SET CLno='%s', SName='%s', SSex= %d, SDate='%s' where SNo=%d", stu.CLno.c_str(), stu.SName.c_str(), stu.SSex, stu.SDate.c_str(), stu.SNo);
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to update data: Error: %s\n", mysql_error(con));
		return false;
	}
	cout << "update sucessful\n";
	return true;
}

vector<Student> StudentManager::get_student(string condition)
{
	vector<Student> stuList;
	char sql[1024];
	sprintf(sql, "select * from student %s", condition.c_str());
	if (mysql_query(con, sql))
	{
		fprintf(stderr, "Failed to select data: Error: %s\n", mysql_error(con));
		return {};
	}
	cout << "select sucessful\n";
	MYSQL_RES* res = mysql_store_result(con);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(res)))
	{
		Student stu;
		stu.SNo = atoi(row[0]);
		stu.CLno = row[1];
		stu.SName = row[2];
		stu.SSex = atoi(row[3]);
		stu.SDate = row[4];
		stuList.push_back(stu);		
	}
	return stuList;
}

main.cpp

#include "StudentManager.h"

int main()
{
	Student stu{ 20059, "020102", "李龟", 0, "2000-04-09" };
	//增加
	StudentManager::GetInstance()->insert_student(stu);
	//更新
	StudentManager::GetInstance()->update_student(stu);
	//删除
	StudentManager::GetInstance()->delete_student(stu);
	//查询
	vector<Student> ret= StudentManager::GetInstance()->get_student("where SSex=1");
	for (auto& t : ret)
	{
		cout << t.SNo << " " << t.SName << " " << t.SDate << endl;
	}
	return 0;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 中操作数据库需要使用数据库 API,比如MySQL的C API或者SQLite的C API。 下面是一个基本的增删改查的例子,以MySQL为例: ```c++ #include <iostream> #include <mysql/mysql.h> int main() { MYSQL *conn = mysql_init(NULL); if (conn == NULL) { std::cerr << "Error: mysql_init()" << std::endl; return EXIT_FAILURE; } if (mysql_real_connect(conn, "localhost", "username", "password", "database", 0, NULL, 0) == NULL) { std::cerr << "Error: mysql_real_connect()" << std::endl; return EXIT_FAILURE; } // 插入数据 std::string insert_sql = "INSERT INTO table_name (col1, col2) VALUES ('value1', 'value2')"; if (mysql_query(conn, insert_sql.c_str()) != 0) { std::cerr << "Error: mysql_query()" << std::endl; return EXIT_FAILURE; } // 删除数据 std::string delete_sql = "DELETE FROM table_name WHERE col = 'value'"; if (mysql_query(conn, delete_sql.c_str()) != 0) { std::cerr << "Error: mysql_query()" << std::endl; return EXIT_FAILURE; } // 更新数据 std::string update_sql = "UPDATE table_name SET col1 = 'new_value' WHERE col2 = 'value2'"; if (mysql_query(conn, update_sql.c_str()) != 0) { std::cerr << "Error: mysql_query()" << std::endl; return EXIT_FAILURE; } // 查询数据 std::string select_sql = "SELECT * FROM table_name"; if (mysql_query(conn, select_sql.c_str()) != 0) { std::cerr << "Error: mysql_query()" << std::endl; return EXIT_FAILURE; } MYSQL_RES *result = mysql_use_result(conn); MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { std::cout << row[0] << "," << row[1] << std::endl; } mysql_free_result(result); mysql_close(conn); return EXIT_SUCCESS; } ``` 需要注意的是,这只是一个简单的例子,实际使用中需要注意SQL注入等安全问题。此外,对于更复杂的数据库操作,可以使用ORM库(比如Qt的QSql)来简化代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值