安装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 😍