在 CentOS 下用 C++ 连接数据库,常见方式取决于你用哪种数据库。下面以 MySQL / MariaDB 和 PostgreSQL 为例,给你最实用的做法。
# CentOS 7
yum install -y mysql-devel
# CentOS 8 / Stream
dnf install -y mysql-devel
#include <mysql/mysql.h>
#include <iostream>
int main() {
MYSQL* conn = mysql_init(nullptr);
if (!conn) {
std::cerr << "mysql_init failed" << std::endl;
return 1;
}
if (!mysql_real_connect(conn,
"localhost",
"user",
"password",
"dbname",
0, nullptr, 0)) {
std::cerr << mysql_error(conn) << std::endl;
return 1;
}
if (mysql_query(conn, "SELECT 1")) {
std::cerr << mysql_error(conn) << std::endl;
}
mysql_close(conn);
return 0;
}
g++ test.cpp -o test -lmysqlclient
yum install -y postgresql-devel
#include <libpq-fe.h>
#include <iostream>
int main() {
PGconn* conn = PQconnectdb(
"host=localhost dbname=test user=postgres password=123456"
);
if (PQstatus(conn) != CONNECTION_OK) {
std::cerr << PQerrorMessage(conn) << std::endl;
return 1;
}
PGresult* res = PQexec(conn, "SELECT 1");
PQclear(res);
PQfinish(conn);
return 0;
}
g++ test.cpp -o test -lpq
yum install -y mysql++-devel
yum install -y unixODBC-devel
yum install mysql-devel
mysqld 是否运行dnf install mariadb-devel
我可以给你更精准的示例和 Makefile / CMake 配置。