当前位置: 首页 > 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;我…...

RestClient

什么是RestClient RestClient 是 Elasticsearch 官方提供的 Java 低级 REST 客户端&#xff0c;它允许HTTP与Elasticsearch 集群通信&#xff0c;而无需处理 JSON 序列化/反序列化等底层细节。它是 Elasticsearch Java API 客户端的基础。 RestClient 主要特点 轻量级&#xff…...

日语学习-日语知识点小记-构建基础-JLPT-N4阶段(33):にする

日语学习-日语知识点小记-构建基础-JLPT-N4阶段(33):にする 1、前言(1)情况说明(2)工程师的信仰2、知识点(1) にする1,接续:名词+にする2,接续:疑问词+にする3,(A)は(B)にする。(2)復習:(1)复习句子(2)ために & ように(3)そう(4)にする3、…...

ssc377d修改flash分区大小

1、flash的分区默认分配16M、 / # df -h Filesystem Size Used Available Use% Mounted on /dev/root 1.9M 1.9M 0 100% / /dev/mtdblock4 3.0M...

FastAPI 教程:从入门到实践

FastAPI 是一个现代、快速&#xff08;高性能&#xff09;的 Web 框架&#xff0c;用于构建 API&#xff0c;支持 Python 3.6。它基于标准 Python 类型提示&#xff0c;易于学习且功能强大。以下是一个完整的 FastAPI 入门教程&#xff0c;涵盖从环境搭建到创建并运行一个简单的…...

基于Uniapp开发HarmonyOS 5.0旅游应用技术实践

一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架&#xff0c;支持"一次开发&#xff0c;多端部署"&#xff0c;可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务&#xff0c;为旅游应用带来&#xf…...

leetcodeSQL解题:3564. 季节性销售分析

leetcodeSQL解题&#xff1a;3564. 季节性销售分析 题目&#xff1a; 表&#xff1a;sales ---------------------- | Column Name | Type | ---------------------- | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | -…...

拉力测试cuda pytorch 把 4070显卡拉满

import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试&#xff0c;通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小&#xff0c;增大可提高计算复杂度duration: 测试持续时间&#xff08;秒&…...

招商蛇口 | 执笔CID,启幕低密生活新境

作为中国城市生长的力量&#xff0c;招商蛇口以“美好生活承载者”为使命&#xff0c;深耕全球111座城市&#xff0c;以央企担当匠造时代理想人居。从深圳湾的开拓基因到西安高新CID的战略落子&#xff0c;招商蛇口始终与城市发展同频共振&#xff0c;以建筑诠释对土地与生活的…...

快刀集(1): 一刀斩断视频片头广告

一刀流&#xff1a;用一个简单脚本&#xff0c;秒杀视频片头广告&#xff0c;还你清爽观影体验。 1. 引子 作为一个爱生活、爱学习、爱收藏高清资源的老码农&#xff0c;平时写代码之余看看电影、补补片&#xff0c;是再正常不过的事。 电影嘛&#xff0c;要沉浸&#xff0c;…...

日常一水C

多态 言简意赅&#xff1a;就是一个对象面对同一事件时做出的不同反应 而之前的继承中说过&#xff0c;当子类和父类的函数名相同时&#xff0c;会隐藏父类的同名函数转而调用子类的同名函数&#xff0c;如果要调用父类的同名函数&#xff0c;那么就需要对父类进行引用&#…...