Connector/C 8.0.39 安装方法
wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
sudo yum clean all
如果直接 yum install mysql-community-devel 会报
获取 GPG 密钥失败:[Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql"
加上
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2023
安装
yum install mysql-community-devel
检查是否安装成功
yum list installed | grep mysql-community-devel
C API 手册
MySQL :: MySQL 8.0 C API Developer Guide :: 4 C API Function Reference
Connector/C++ 8.4.0
官网: MySQL :: Download MySQL Connector/C++ (Archived Versions)
将下载好的文件中的 include下所有文件 拷贝到 /usr/local/include中,也可以新建一个文件夹存放例如 /usr/local/include/mysql-cppconn-8 ,但需要在CMakeLists中描述清楚。lib64下的所有文件也同理放到 /usr/local/lib64下。
#include <iostream>
#include <mysql-cppconn-8/mysql/jdbc.h>
// #include <mysql/mysql.h>
using namespace std;
using namespace sql;
class MysqlBase {
public:
bool ConnectInit() {
try {
// 获取 MySQL 驱动实例
driver = sql::mysql::get_mysql_driver_instance();
// 连接到 MySQL 数据库
connection.reset(driver->connect("tcp://127.0.0.1:33060", "root", "aoliao"));
// 选择数据库
connection->setSchema("cgame");
return true;
} catch (sql::SQLException& e) {
cerr << "Connection error: " << e.what() << endl;
return false;
}
}
virtual void Disconnect() {
if (connection) {
connection->close();
}
}
bool Query(const char* sql) {
try {
// 创建 Statement 对象
sql::Statement* stmt = connection->createStatement();
// 执行查询
sql::ResultSet* res = stmt->executeQuery(sql);
// 处理结果集
while (res->next()) {
// 访问第一列的值(假设第一列是字符串)
cout << "Column 1: " << res->getString(1) << endl;
}
// 清理
delete res;
delete stmt;
return true;
} catch (sql::SQLException& e) {
cerr << "Query error: " << e.what() << endl;
return false;
}
}
private:
sql::mysql::MySQL_Driver* driver;
unique_ptr<sql::Connection> connection;
};
int main() {
MysqlBase mysql;
// 初始化连接
if (!mysql.ConnectInit()) {
cerr << "Failed to connect to the database." << endl;
return 1;
}
// 执行查询
if (!mysql.Query("SELECT * FROM account LIMIT 10")) {
cerr << "Failed to execute query." << endl;
mysql.Disconnect();
return 1;
}
// 断开连接
mysql.Disconnect();
return 0;
}
[root@localhost dbmgr]# g++ -o mysql_test mysql_test.cpp -I/usr/include/mysql-cppconn-8 -L/usr/local/lib64/mysql-cppconn-8 -L/usr/local/lib64/mysql-cppconn-8/private -lmysqlcppconn -lssl -lcrypto
[root@localhost dbmgr]# ./mysql_test
Column 1: 1000
Column 1: 1001
Column 1: 1002
Column 1: 1003
Column 1: 1004
Column 1: 1005
Column 1: 1006
Column 1: 1007
Column 1: 1008
Column 1: 1009
[root@localhost dbmgr]#