当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 161861提问 提问时间:2023-11-04 14:30:01阅读次数: 61

最佳答案 问答题库618位专家为你答疑解惑

目录

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)

运行前:

运行后:

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"MySQL笔记--Ubuntu安装MySQL并基于C++测试API":http://eshow365.cn/6-31877-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!