使用mysqlclient庫連線mysql

杨谖之發表於2024-04-20

使用mysqlclient庫連線mysql

安裝mysqlclient庫

yum install mariadb mariadb-server mariadb-devel mariadb-libs luarocks lua-devel
yum group install "Development Tools"

例程

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "mysql.h"
using namespace std;

int main() {
    MYSQL *mysql = mysql_init(nullptr);
    if (mysql == nullptr) {
        cerr << "Mysql物件初始化失敗!" << endl;
        exit(-1);
    }
    clog << "Mysql物件初始化成功!" << endl;

    MYSQL *conn = mysql_real_connect(mysql, "192.168.0.182", "remote", "Mysql_abc123", "test", 0, nullptr, 0);
    if (conn == nullptr) {
        cerr << mysql_error(mysql) << endl;
        exit(-1);
    }
    clog << "Connect MySQL OK, [" << mysql << "], [" << conn << "]" << endl;

    // 執行SQL語句
    if (mysql_query(conn, "select * from test;") != 0) {
        cerr << mysql_error(mysql) << endl;
    } else {
        MYSQL_RES *result = mysql_store_result(conn);
        MYSQL_ROW row = nullptr;
        uint col_num = mysql_num_fields(result);
        uint row_num = mysql_num_rows(result);
        cout << "行數:" << row_num << "\t列數:" << col_num << endl;
        // 獲取列名
        MYSQL_FIELD *fields = mysql_fetch_fields(result);
        for (int i = 0; i < col_num; i++) {
            cout << fields[i].name << '\t';
        }
        cout << endl;
        // 獲取資料
        while ((row = mysql_fetch_row(result)) != nullptr) {
            cout << row[0] << "\t" << row[1] << "\t\t" << row[2] << endl;
        }
        mysql_free_result(result);
    }

    mysql_close(conn);

    return 0;
}

相關文章