在CentOS上使用C++连接数据库,通常需要使用数据库提供的客户端库。以下是一些常见数据库的C++连接操作步骤:
安装MySQL客户端库
sudo yum install mysql-devel
编写C++代码
使用MySQL提供的C API,例如mysql.h
和mysqld.h
。
#include <mysql/mysql.h>
#include <iostream>
int main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, "localhost", "user", "password", "database", 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
if (mysql_query(conn, "SELECT * FROM table")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL) {
std::cout << row[0] << std::endl;
}
mysql_free_result(res);
mysql_close(conn);
return 0;
}
编译代码
g++ -o mysql_example mysql_example.cpp -lmysqlclient
运行程序
./mysql_example
安装PostgreSQL客户端库
sudo yum install postgresql-devel
编写C++代码
使用PostgreSQL提供的C API,例如libpq-fe.h
。
#include <pqxx/pqxx>
#include <iostream>
int main() {
try {
pqxx::connection C("dbname=database user=user password=password hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
std::cout << "Opened database successfully: " << C.dbname() << std::endl;
pqxx::work W(C);
pqxx::result R = W.exec("SELECT * FROM table");
for (auto row : R) {
std::cout << row[0].as<std::string>() << std::endl;
}
W.commit();
} else {
std::cout << "Can't open database" << std::endl;
return 1;
}
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
编译代码
g++ -o postgresql_example postgresql_example.cpp -lpqxx -lpq
运行程序
./postgresql_example
安装SQLite
sudo yum install sqlite-devel
编写C++代码
使用SQLite提供的C API,例如sqlite3.h
。
#include <sqlite3.h>
#include <iostream>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
for (int i = 0; i < argc; i++) {
std::cout << azColName[i] << ": " << (argv[i] ? argv[i] : "NULL") << std::endl;
}
std::cout << std::endl;
return 0;
}
int main() {
sqlite3 *db;
char *err_msg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if (rc != SQLITE_OK) {
std::cerr << "Cannot open database: " << sqlite3_errmsg(db) << std::endl;
sqlite3_close(db);
return 1;
}
rc = sqlite3_exec(db, "SELECT * FROM table", callback, 0, &err_msg);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << err_msg << std::endl;
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
return 0;
}
编译代码
g++ -o sqlite_example sqlite_example.cpp -lsqlite3
运行程序
./sqlite_example
以上步骤展示了如何在CentOS上使用C++连接不同类型的数据库。每种数据库都有其特定的客户端库和API,因此需要根据具体的数据库类型选择合适的库和API进行操作。编译时需要链接相应的库文件。