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)
运行前:
运行后:
相关文章:

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…...

与AI对话的艺术:如何优化Prompt以获得更好的响应反馈
前言 在当今数字化时代,人工智能系统已经成为我们生活的一部分。我们可以在智能助手、聊天机器人、搜索引擎等各种场合与AI进行对话。然而,要获得有益的回应,我们需要学会与AI进行有效的沟通,这就涉及到如何编写好的Prompt。 与…...

outlook是什么软件outlook邮箱撤回邮件方法
Outlook是微软公司开发的一款邮件客户端,也是Office办公套件的一部分。它可以与多个电子邮件服务提供商(如Outlook.com、Exchange、Gmail等)集成,用户可以使用Outlook来发送、接收和管理电子邮件、日历、联系人、任务等信息。本篇…...

电脑如何录制小视频
如果你想在你的电脑上录制视频分享给你的朋友或者亲人,无论你的电脑是win还是mac,都可以在本篇文章中找到电脑录制视频的详细教程。小编为你们整理了2种不同系统电脑的录制详细流程,继续阅读查看吧! 第一部分:windows…...

vue使用百度富文本
🔥博客主页: 破浪前进 🔖系列专栏: Vue、React、PHP ❤️感谢大家点赞👍收藏⭐评论✍️ 1、下载UEditor 链接已放到文章中了 2、上传到项目目录中 一般上传到public下,方便到时候打包进去,以免…...

【Springboot】集成Swagger
引入依赖 <dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version> </dependency> 浏览器 启动项目后 在浏览器中输入地址 localhost:端口号/swagger-ui/ 使…...

[SpringCloud | Linux] CentOS7 部署 SpringCloud 微服务
目录 一、环境准备 1、工具准备 2、虚拟机环境 3、Docker 环境 二、项目准备 1、配置各个模块(微服务)的 Dockerfile 2、配置 docker-compose.yml 文件 3、Maven 打包 4、文件整合并传输 三、微服务部署 1、部署至 Docker 2、访问微服务 四…...

阿里面试:让代码不腐烂,DDD是怎么做的?
说在前面 在40岁老架构师 尼恩的读者交流群(50)中,最近有小伙伴拿到了一线互联网企业如阿里、滴滴、极兔、有赞、希音、百度、网易、美团的面试资格,遇到很多很重要的面试题: 谈谈你的高并发落地经验? 谈谈你对DDD的理解…...

NoSQL数据库使用场景以及架构介绍
文章目录 一. 什么是NoSQL?二. NoSQL分类三. NoSQL与关系数据库有什么区别四. NoSQL主要优势和缺点五. NoSQL体系框架 其它相关推荐: 系统架构之微服务架构 系统架构设计之微内核架构 鸿蒙操作系统架构 架构设计之大数据架构(Lambda架构、Kap…...

RFID系统提升物流信息管理效率应用解决方案
一、物流仓储管理方法 1、在仓库的进出口处安装RFID读写器,当粘贴RFID标签的电动叉车和货物进入装载区时,RFID读写器会自动检索并记录信息,当它们离开物流配送中心时,入口处的RFID读写器会读取标签信息,并生成出货单&…...

ONNX的结构与转换
ONNX的结构与转换 1. 背景2. ONNX结构分析与修改工具2.1. ONNX结构分析2.2. ONNX的兼容性问题2.3. 修改ONNX模型 3. 各大深度学习框架如何转换到ONNX?3.1. MXNet转换ONNX3.2. TensorFlow模型转ONNX3.3. PyTorch模型转ONNX3.4. PaddlePaddle模型转ONNX3.4.1. 简介3.4…...

vue3中,使用html2canvas截图包含视频、图片、文字的区域
需求:将页面中指定区域进行截图,区域中包含了图片、文字、视频。 第一步,先安装 npm install html2canvas第二步,在页面引入: import html2canvas from html2canvas;第三步,页面使用: 1&…...

后端神器!代码写完直接调试!
Apipost推出IDEA插件非常省时高效,写完代码直接可以进行调试,而且支持生成接口文档,真是后端神器啊! 可以点击下方链接安装更新或在插件商店中搜索安装 下载链接:https://plugins.jetbrains.com/plugin/22676-apipos…...

MATLAB | 万圣节来画个简单的可爱鬼叭!
万圣节要到啦一起来画个可爱鬼吧~ 代码比较的短: 完整代码 figure(Units,normalized,Position,[.2,.1,.52,.72]); axgca;hold on;axis off; ax.DataAspectRatio[1,1,1]; ax.YDirreverse; ax.XLim[0,100]; ax.YLim[0,100]; [X,Y]meshgrid(linspace(0,1,200)); Zsq…...

贪心算法学习------优势洗牌
目录 一,题目 二,题目接口 三,解题思路和代码 全部代码: 一,题目 给定两个数组nums1和nums2,nums1相对于nums2的优势可以用满足nums1[i]>nums2[i]的索引i的数目来描述。 返回nums1的任意排序,使其优…...

音视频rtsp rtmp gb28181在浏览器上的按需拉流
按需拉流是从客户视角来看待音视频的产品功能,直观,好用,为啥hls flv大行其道也是这个原因,不过上述存在的问题是延迟没法降到实时毫秒级延迟,也不能随心所欲的控制。通过一段时间的努力,结合自己闭环技术栈…...

Java 算法篇-深入了解二分查找法
🔥博客主页: 小扳_-CSDN博客 ❤感谢大家点赞👍收藏⭐评论✍ 目录 1.0 二分查找法的说明 2.0 二分查找实现的多种版本 2.1 二分查找的基础版本 2.2 二分查找的改动版本 2.3 二分查找的平衡版本 2.4 二分查找的官方版本 3.0 二分查找的应用 1…...
Data-Centric Financial Large Language Models
本文是LLM系列文章,针对《Data-Centric Financial Large Language Models》的翻译。 以数据为中心的大语言金融模型 摘要1 引言2 背景3 方法4 实验5 结论和未来工作 摘要 大型语言模型(LLM)有望用于自然语言任务,但在直接应用于…...

【HarmonyOS】服务卡片 API6 JSUI跳转不同页面并携带参数
【关键字】 服务卡片、卡片跳转不同页面、卡片跳转页面携带参数 【写在前面】 本篇文章主要介绍开发服务卡片时,如何实现卡片点击跳转不同页面,并携带动态参数到js页面。在此篇文章“服务卡片 API6 JSUI跳转不同页面”中说明了如果跳转不同页面…...

SQL server数据库端口访问法
最近数据库连接,也是无意中发现了这个问题,数据库可根据端口来连接 网址:yii666.com< 我用的是sql2014测试的,在安装其他程序是默认安装了sql(sql的tcp/ip端口为xxx),服务也不相同,但是由于比较不全,我…...

【Axure高保真原型】引导弹窗
今天和大家中分享引导弹窗的原型模板,载入页面后,会显示引导弹窗,适用于引导用户使用页面,点击完成后,会显示下一个引导弹窗,直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…...

接口测试中缓存处理策略
在接口测试中,缓存处理策略是一个关键环节,直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性,避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明: 一、缓存处理的核…...
云原生核心技术 (7/12): K8s 核心概念白话解读(上):Pod 和 Deployment 究竟是什么?
大家好,欢迎来到《云原生核心技术》系列的第七篇! 在上一篇,我们成功地使用 Minikube 或 kind 在自己的电脑上搭建起了一个迷你但功能完备的 Kubernetes 集群。现在,我们就像一个拥有了一块崭新数字土地的农场主,是时…...

CTF show Web 红包题第六弹
提示 1.不是SQL注入 2.需要找关键源码 思路 进入页面发现是一个登录框,很难让人不联想到SQL注入,但提示都说了不是SQL注入,所以就不往这方面想了 先查看一下网页源码,发现一段JavaScript代码,有一个关键类ctfs…...
golang循环变量捕获问题
在 Go 语言中,当在循环中启动协程(goroutine)时,如果在协程闭包中直接引用循环变量,可能会遇到一个常见的陷阱 - 循环变量捕获问题。让我详细解释一下: 问题背景 看这个代码片段: fo…...

理解 MCP 工作流:使用 Ollama 和 LangChain 构建本地 MCP 客户端
🌟 什么是 MCP? 模型控制协议 (MCP) 是一种创新的协议,旨在无缝连接 AI 模型与应用程序。 MCP 是一个开源协议,它标准化了我们的 LLM 应用程序连接所需工具和数据源并与之协作的方式。 可以把它想象成你的 AI 模型 和想要使用它…...
Frozen-Flask :将 Flask 应用“冻结”为静态文件
Frozen-Flask 是一个用于将 Flask 应用“冻结”为静态文件的 Python 扩展。它的核心用途是:将一个 Flask Web 应用生成成纯静态 HTML 文件,从而可以部署到静态网站托管服务上,如 GitHub Pages、Netlify 或任何支持静态文件的网站服务器。 &am…...
Java 加密常用的各种算法及其选择
在数字化时代,数据安全至关重要,Java 作为广泛应用的编程语言,提供了丰富的加密算法来保障数据的保密性、完整性和真实性。了解这些常用加密算法及其适用场景,有助于开发者在不同的业务需求中做出正确的选择。 一、对称加密算法…...
JDK 17 新特性
#JDK 17 新特性 /**************** 文本块 *****************/ python/scala中早就支持,不稀奇 String json “”" { “name”: “Java”, “version”: 17 } “”"; /**************** Switch 语句 -> 表达式 *****************/ 挺好的ÿ…...
实现弹窗随键盘上移居中
实现弹窗随键盘上移的核心思路 在Android中,可以通过监听键盘的显示和隐藏事件,动态调整弹窗的位置。关键点在于获取键盘高度,并计算剩余屏幕空间以重新定位弹窗。 // 在Activity或Fragment中设置键盘监听 val rootView findViewById<V…...