当前位置: 首页 > news >正文

MySQL笔记--Ubuntu安装MySQL并基于C++测试API

目录

1--安装MySQL

2--MySQL连接

3--代码案例


1--安装MySQL

# 安装MySQL-Server
sudo apt install mysql-server# 设置系统启动时自动开启
sudo systemctl start mysql
# sudo systemctl enable mysql# 检查MySQL运行状态
sudo systemctl status mysql# 进入MySQL终端
sudo mysql# 更改root密码为123456
alter user 'root'@'localhost' identified with mysql_native_password by '123456';# 退出MySQL终端
exit# 以root用户登录
mysql -u root -p

2--MySQL连接

① 首先安装依赖:

sudo apt-get install libmysqlclient-dev

② 测试连接:

先在终端创建一个测试数据库,并新建一个测试表:

# 进入MySQL终端
mysql -u root -p# 创建数据库
create database test_by_ljf;# 进入数据库
use test_by_ljf;# 创建表
create table Stu_table(id int comment 'ID',name varchar(20) comment 'Name of Student',class varchar(10) comment 'Class of Student'
) comment 'Table of Student';

③ 测试代码:

// 包含头文件
#include <iostream>
#include <string>
#include <mysql/mysql.h>// 定义数据库连接参数
const char* host = "127.0.0.1";
const char* user = "root";
const char* pw = "123456";
const char* database_name = "test_by_ljf";
const int port = 3306;// 定义学生结构体
struct Student{
public:int student_id;std::string student_name;std::string class_id;
};int main(int argc, char* argv[]){// 初始化MYSQL* con = mysql_init(NULL);// 连接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 stu1{1, "big_clever", "class 1"};// 语法 "insert into 表名 (字段1, ...) values (值1, ...)""char sql[256];sprintf(sql, "insert into Stu_table (id, name, class) values (%d, '%s', '%s')",stu1.student_id, stu1.student_name.c_str(), stu1.class_id.c_str());// 插入学生对象if(mysql_query(con, sql)){fprintf(stderr, "Failed to insert data : Error:%s\n", mysql_error(con));return -1;}// 关闭连接mysql_close(con);return 0;
}

编译时需要加上 -lmysqlclient 依赖;

3--代码案例

案例分析:

        封装一个学生类,实现对上面学生表的增删改查操作;

头文件:

#pragma once
#include <mysql/mysql.h>
#include <iostream>
#include <string>
#include <vector>// 定义学生结构体
struct Student{
public:int student_id;std::string student_name;std::string class_id;
};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); // 删除std::vector<Student> get_student(std::string condition = ""); // 查询private:MYSQL* con;// 定义数据库连接参数const char* host = "127.0.0.1";const char* user = "root";const char* pw = "123456";const char* database_name = "test_by_ljf";const int port = 3306;
};

源文件:

#include "StudentManager.h"StudentManager::StudentManager(){this->con = mysql_init(NULL); // 初始化// 连接if(!mysql_real_connect(this->con, this->host, this->user, this->pw, this->database_name, this->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[256];sprintf(sql, "insert into Stu_table (id, name, class) 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_error(con));return false;}return true;
}bool StudentManager::update_student(Student& stu){char sql[256];sprintf(sql, "update Stu_table set name = '%s', class = '%s'" "where 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_error(con));return false;}return true;
}bool StudentManager::delete_student(int student_id){char sql[256];sprintf(sql, "delete from Stu_table where id = %d", student_id);if(mysql_query(con, sql)){fprintf(stderr, "Failed to delete data : Error:%s\n", mysql_error(con));return false;}return true;
}std::vector<Student> StudentManager::get_student(std::string condition){char sql[256];sprintf(sql, "select * from Stu_table %s", condition.c_str());if(mysql_query(con, sql)){fprintf(stderr, "Failed to select data : Error:%s\n", mysql_error(con));return {};}std::vector<Student> stuList;MYSQL_RES* res = mysql_store_result(con);MYSQL_ROW row;while((row = mysql_fetch_row(res))){Student stu;stu.student_id = std::atoi(row[0]);stu.student_name = row[1];stu.class_id = row[2];stuList.push_back(stu);}return stuList;
}

测试函数:

#include <StudentManager.h>int main(int argc, char* argv[]){Student stu2{2, "small clever", "class 2"};StudentManager::GetInstance()->insert_student(stu2); // 测试插入Student stu1{1, "big big clever", "class 1"}; // 测试更新StudentManager::GetInstance()->update_student(stu1);std::string condition = "where class = 'class 2'";std::vector<Student> res = StudentManager::GetInstance()->get_student(condition); // 测试查询for(Student stu_test : res){std::cout << "id: " << stu_test.student_id << " name: " << stu_test.student_name << " class: " << stu_test.class_id << std::endl;}StudentManager::GetInstance()->delete_student(2); // 测试删除return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)project(Test)set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_STANDARD 11)include_directories(${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/include)
file(GLOB_RECURSE SRCS ${PROJECT_SOURCE_DIR}/src/*.cpp)add_executable(main test.cpp ${SRCS})
target_link_libraries(main -lmysqlclient)

运行前:

运行后:

相关文章:

  • web3 在React dapp中全局管理web3当前登录用户/智能合约等信息
  • conda配置虚拟环境相关记录
  • 利用wasm实现读写本地项目的在线编辑器
  • IDEA 使用技巧
  • javaEE -15( 13000字 JavaScript入门 - 2)
  • 【Linux】服务器间免登陆访问
  • docker安装Kafka,SpringBoot整合Kafka
  • IOC课程整理-11 Spring 资源管理
  • Failed to launch task: 文件”Setup”不存在 Mac安装Adobe软件报错解决方案
  • 微服务的定义
  • string【C++】
  • 数据库 | 看这一篇就够了!最全MySQL数据库知识框架!
  • Spring MVC(Next-2)
  • 十种排序算法(1) - 准备测试函数和工具
  • 生态扩展Spark Doris Connector
  • [微信小程序] 使用ES6特性Class后出现编译异常
  • Codepen 每日精选(2018-3-25)
  • GDB 调试 Mysql 实战(三)优先队列排序算法中的行记录长度统计是怎么来的(上)...
  • IIS 10 PHP CGI 设置 PHP_INI_SCAN_DIR
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • Python中eval与exec的使用及区别
  • vagrant 添加本地 box 安装 laravel homestead
  • vue--为什么data属性必须是一个函数
  • 解决jsp引用其他项目时出现的 cannot be resolved to a type错误
  • 开源SQL-on-Hadoop系统一览
  • 理解 C# 泛型接口中的协变与逆变(抗变)
  • 聊聊spring cloud的LoadBalancerAutoConfiguration
  • 排序算法之--选择排序
  • 区块链共识机制优缺点对比都是什么
  • 删除表内多余的重复数据
  • 体验javascript之美-第五课 匿名函数自执行和闭包是一回事儿吗?
  • ​你们这样子,耽误我的工作进度怎么办?
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • (02)vite环境变量配置
  • (3)(3.2) MAVLink2数据包签名(安全)
  • (6)STL算法之转换
  • (保姆级教程)Mysql中索引、触发器、存储过程、存储函数的概念、作用,以及如何使用索引、存储过程,代码操作演示
  • (附源码)apringboot计算机专业大学生就业指南 毕业设计061355
  • (原)记一次CentOS7 磁盘空间大小异常的解决过程
  • .describe() python_Python-Win32com-Excel
  • .MSSQLSERVER 导入导出 命令集--堪称经典,值得借鉴!
  • .NET Conf 2023 回顾 – 庆祝社区、创新和 .NET 8 的发布
  • .NET CORE Aws S3 使用
  • .NET core 自定义过滤器 Filter 实现webapi RestFul 统一接口数据返回格式
  • .Net Core缓存组件(MemoryCache)源码解析
  • .NET gRPC 和RESTful简单对比
  • .NET Micro Framework初体验(二)
  • .net 程序 换成 java,NET程序员如何转行为J2EE之java基础上(9)
  • .NET/C# 使用反射注册事件
  • .Net接口调试与案例
  • .Net中间语言BeforeFieldInit
  • @KafkaListener注解详解(一)| 常用参数详解
  • @media screen 针对不同移动设备
  • @private @protected @public
  • @RequestBody的使用