wsl ubuntu24.04 安装 mariadb 11.8.6 c++ 操作实例

安装mariadb11.8 lts版本

因为mariadb11.8是最新的lts版本只能使用官方仓库安装

先下载官方脚本

复制代码
curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup -o mariadb_repo_setup
chmod +x mariadb_repo_setup
./mariadb_repo_setup --mariadb-server-version=11.8

更新系统 安装mariadb相关软件

复制代码
apt update -y
apt install libzstd-dev -y
apt install curl ca-certificates gnupg -y
apt install mariadb-server mariadb-client -y
apt install libmariadb-dev -y

创建数据库

复制代码
CREATE DATABASE aa DEFAULT CHARSET utf8mb4;

USE aa;

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    age INT,
    phone VARCHAR(20)
);

INSERT INTO users(name, age, phone)
VALUES ('张三', 20, '13800000000');

root连接失败创建普通用户

复制代码
CREATE DATABASE IF NOT EXISTS aa;

CREATE USER 'app'@'127.0.0.1' IDENTIFIED BY '123456';

GRANT ALL PRIVILEGES ON aa.* TO 'app'@'127.0.0.1';

FLUSH PRIVILEGES;

db.hpp

复制代码
#pragma once
#include <mysql.h>
#include <string>
#include <vector>

struct User {
    std::string name;
    int age;
    std::string phone;
};

struct DbResult {
    bool success;
    std::string message;
};

class Database {
public:
    Database(const std::string& host,
             const std::string& user,
             const std::string& password,
             const std::string& dbname,
             unsigned int port = 3306);

    ~Database();

    bool connect();

    std::vector<User> queryUsers();

    DbResult insertUser(const std::string& name, int age, const std::string& phone);

    std::string lastError() const;

private:
    MYSQL* conn_;
    std::string host_, user_, password_, dbname_;
    unsigned int port_;
};

db.cpp

复制代码
#include "db.hpp"
#include <sstream>

Database::Database(const std::string& host,
                   const std::string& user,
                   const std::string& password,
                   const std::string& dbname,
                   unsigned int port)
    : host_(host), user_(user), password_(password),
      dbname_(dbname), port_(port)
{
    conn_ = mysql_init(nullptr);
}

Database::~Database() {
    if (conn_) {
        mysql_close(conn_);
    }
}

bool Database::connect() {
    if (!mysql_real_connect(conn_,
                            host_.c_str(),
                            user_.c_str(),
                            password_.c_str(),
                            dbname_.c_str(),
                            port_,
                            nullptr,
                            0))
    {
        return false;
    }
    return true;
}

std::vector<User> Database::queryUsers() {
    std::vector<User> users;

    if (mysql_query(conn_, "SELECT name, age, phone FROM users")) {
        return users;
    }

    MYSQL_RES* result = mysql_store_result(conn_);
    if (!result) return users;

    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        User u;
        u.name = row[0] ? row[0] : "";
        u.age = row[1] ? std::stoi(row[1]) : 0;
        u.phone = row[2] ? row[2] : "";
        users.push_back(u);
    }

    mysql_free_result(result);
    return users;
}

DbResult Database::insertUser(const std::string& name, int age, const std::string& phone) {
    std::stringstream ss;
    ss << "INSERT INTO users(name, age, phone) VALUES('"
       << name << "', "
       << age << ", '"
       << phone << "')";

    if (mysql_query(conn_, ss.str().c_str())) {
        return {false, mysql_error(conn_)};
    }

    return {true, "Insert success"};
}

std::string Database::lastError() const {
    return mysql_error(conn_);
}

main.cpp

复制代码
#include "db.hpp"
#include <iostream>

int main() {
    Database db("127.0.0.1", "app", "123456", "aa");
    // Database db("127.0.0.1", "root", "", "aa");
    if (!db.connect()) {
	std::cout << "Connect failed: "
              << db.lastError()
              << std::endl;
        return 1;
    }

    std::cout << "查询数据库信息\n";
    std::cout << "======================================================================\n";
    auto users = db.queryUsers();
    for (const auto& u : users) {
        std::cout << u.name << " "
                  << u.age << " "
                  << u.phone << "\n";
    }
    std::cout << "======================================================================\n";

    // 开始插入
    std::cout << "@@@@@@@@开始插入@@@@@@@@\n";

    auto res = db.insertUser("张三", 23,"13800000000");
    
    if (res.success)
    {
        std::cout << "Insert: success" << " - " << res.message << "\n";
    }
    else
    {
        std::cout << "Insert: failed" << " - " << res.message << "\n";
        return 0;
    }
    res = db.insertUser("李四", 25, "13900000000");
    if (res.success)
    {
        std::cout << "Insert: success" << " - " << res.message << "\n";
    }
    else
    {
        std::cout << "Insert: failed" << " - " << res.message << "\n";
        return 0;
    }

    std::cout << "@@@@@@@@结束插入@@@@@@@@\n";
    // users = db.queryUsers();
    // for (const auto& u : users) {
    //     std::cout << u.name << " "
    //               << u.age << " "
    //               << u.phone << "\n";
    // }

    return 0;
}

编译

复制代码
g++ -std=c++20 main.cpp db.cpp -o app -I/usr/include/mariadb /usr/lib/x86_64-linux-gnu/libmariadb.a -lz -lssl -lcrypto -ldl -lpthread

卸载

复制代码
apt purge mariadb-server mariadb-client mariadb-common mariadb-server-core-* mariadb-client-core-* libmariadb* -y
rm -rf /var/lib/mysql
rm -rf /etc/mysql
rm -rf /etc/apt/sources.list.d/mariadb*
apt autoremove -y
apt autoclean
apt clean
dpkg -l | grep maria
dpkg --purge mysql-common

后续:修改phone为主键

复制代码
USE aa;

-- 查看结构
discribe users;
-- 1. 先删除主键(这会报错,所以需要先处理 AUTO_INCREMENT)
-- 先修改 id,去掉 AUTO_INCREMENT
ALTER TABLE users MODIFY id INT NOT NULL;

-- 2. 删除主键
ALTER TABLE users DROP PRIMARY KEY;

-- 3. 将 phone 改为 NOT NULL 并设为主键
ALTER TABLE users MODIFY phone VARCHAR(20) NOT NULL;
ALTER TABLE users ADD PRIMARY KEY (phone);

-- 4. 可选:给 id 添加普通索引(如果需要保留 id 的查询性能)
ALTER TABLE users ADD INDEX idx_id (id);


ALTER TABLE users MODIFY id INT AUTO_INCREMENT;

Enjoy 😍

相关推荐
端平入洛21 小时前
auto有时不auto
c++
爱可生开源社区1 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1771 天前
《从零搭建NestJS项目》
数据库·typescript
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1232 天前
matlab画图工具
开发语言·matlab
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏2 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
dustcell.2 天前
haproxy七层代理
java·开发语言·前端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
李慕婉学姐2 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端