当前位置: 首页 > 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)

运行前:

运行后:

相关文章:

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以获得更好的响应反馈

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

outlook是什么软件outlook邮箱撤回邮件方法

Outlook是微软公司开发的一款邮件客户端&#xff0c;也是Office办公套件的一部分。它可以与多个电子邮件服务提供商&#xff08;如Outlook.com、Exchange、Gmail等&#xff09;集成&#xff0c;用户可以使用Outlook来发送、接收和管理电子邮件、日历、联系人、任务等信息。本篇…...

电脑如何录制小视频

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

vue使用百度富文本

&#x1f525;博客主页&#xff1a; 破浪前进 &#x1f516;系列专栏&#xff1a; Vue、React、PHP ❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 1、下载UEditor 链接已放到文章中了 2、上传到项目目录中 一般上传到public下&#xff0c;方便到时候打包进去&#xff0c;以免…...

【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、配置各个模块&#xff08;微服务&#xff09;的 Dockerfile 2、配置 docker-compose.yml 文件 3、Maven 打包 4、文件整合并传输 三、微服务部署 1、部署至 Docker 2、访问微服务 四…...

阿里面试:让代码不腐烂,DDD是怎么做的?

说在前面 在40岁老架构师 尼恩的读者交流群(50)中&#xff0c;最近有小伙伴拿到了一线互联网企业如阿里、滴滴、极兔、有赞、希音、百度、网易、美团的面试资格&#xff0c;遇到很多很重要的面试题&#xff1a; 谈谈你的高并发落地经验&#xff1f; 谈谈你对DDD的理解&#xf…...

NoSQL数据库使用场景以及架构介绍

文章目录 一. 什么是NoSQL&#xff1f;二. NoSQL分类三. NoSQL与关系数据库有什么区别四. NoSQL主要优势和缺点五. NoSQL体系框架 其它相关推荐&#xff1a; 系统架构之微服务架构 系统架构设计之微内核架构 鸿蒙操作系统架构 架构设计之大数据架构&#xff08;Lambda架构、Kap…...

RFID系统提升物流信息管理效率应用解决方案

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

ONNX的结构与转换

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

vue3中,使用html2canvas截图包含视频、图片、文字的区域

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

后端神器!代码写完直接调试!

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

MATLAB | 万圣节来画个简单的可爱鬼叭!

万圣节要到啦一起来画个可爱鬼吧~ 代码比较的短&#xff1a; 完整代码 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…...

贪心算法学习------优势洗牌

目录 一&#xff0c;题目 二&#xff0c;题目接口 三&#xff0c;解题思路和代码 全部代码&#xff1a; 一&#xff0c;题目 给定两个数组nums1和nums2,nums1相对于nums2的优势可以用满足nums1[i]>nums2[i]的索引i的数目来描述。 返回nums1的任意排序&#xff0c;使其优…...

音视频rtsp rtmp gb28181在浏览器上的按需拉流

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

Java 算法篇-深入了解二分查找法

&#x1f525;博客主页&#xff1a; 小扳_-CSDN博客 ❤感谢大家点赞&#x1f44d;收藏⭐评论✍ 目录 1.0 二分查找法的说明 2.0 二分查找实现的多种版本 2.1 二分查找的基础版本 2.2 二分查找的改动版本 2.3 二分查找的平衡版本 2.4 二分查找的官方版本 3.0 二分查找的应用 1…...

Data-Centric Financial Large Language Models

本文是LLM系列文章&#xff0c;针对《Data-Centric Financial Large Language Models》的翻译。 以数据为中心的大语言金融模型 摘要1 引言2 背景3 方法4 实验5 结论和未来工作 摘要 大型语言模型&#xff08;LLM&#xff09;有望用于自然语言任务&#xff0c;但在直接应用于…...

【HarmonyOS】服务卡片 API6 JSUI跳转不同页面并携带参数

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

SQL server数据库端口访问法

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

基于大模型的 UI 自动化系统

基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...

大话软工笔记—需求分析概述

需求分析&#xff0c;就是要对需求调研收集到的资料信息逐个地进行拆分、研究&#xff0c;从大量的不确定“需求”中确定出哪些需求最终要转换为确定的“功能需求”。 需求分析的作用非常重要&#xff0c;后续设计的依据主要来自于需求分析的成果&#xff0c;包括: 项目的目的…...

YSYX学习记录(八)

C语言&#xff0c;练习0&#xff1a; 先创建一个文件夹&#xff0c;我用的是物理机&#xff1a; 安装build-essential 练习1&#xff1a; 我注释掉了 #include <stdio.h> 出现下面错误 在你的文本编辑器中打开ex1文件&#xff0c;随机修改或删除一部分&#xff0c;之后…...

Mac软件卸载指南,简单易懂!

刚和Adobe分手&#xff0c;它却总在Library里给你写"回忆录"&#xff1f;卸载的Final Cut Pro像电子幽灵般阴魂不散&#xff1f;总是会有残留文件&#xff0c;别慌&#xff01;这份Mac软件卸载指南&#xff0c;将用最硬核的方式教你"数字分手术"&#xff0…...

土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等

&#x1f50d; 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术&#xff0c;可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势&#xff0c;还能有效评价重大生态工程…...

MySQL 8.0 OCP 英文题库解析(十三)

Oracle 为庆祝 MySQL 30 周年&#xff0c;截止到 2025.07.31 之前。所有人均可以免费考取原价245美元的MySQL OCP 认证。 从今天开始&#xff0c;将英文题库免费公布出来&#xff0c;并进行解析&#xff0c;帮助大家在一个月之内轻松通过OCP认证。 本期公布试题111~120 试题1…...

初学 pytest 记录

安装 pip install pytest用例可以是函数也可以是类中的方法 def test_func():print()class TestAdd: # def __init__(self): 在 pytest 中不可以使用__init__方法 # self.cc 12345 pytest.mark.api def test_str(self):res add(1, 2)assert res 12def test_int(self):r…...

算法笔记2

1.字符串拼接最好用StringBuilder&#xff0c;不用String 2.创建List<>类型的数组并创建内存 List arr[] new ArrayList[26]; Arrays.setAll(arr, i -> new ArrayList<>()); 3.去掉首尾空格...

保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek

文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama&#xff08;有网络的电脑&#xff09;2.2.3 安装Ollama&#xff08;无网络的电脑&#xff09;2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...

C++.OpenGL (20/64)混合(Blending)

混合(Blending) 透明效果核心原理 #mermaid-svg-SWG0UzVfJms7Sm3e {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-icon{fill:#552222;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-text{fill…...