使用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;
}