引言:为什么要在C++中连接数据库
现代C++应用程序很少能脱离持久化数据存储。无论是游戏服务器、遥测系统还是高负载后端,都需要与数据库管理系统交互。目前市场上主要有两种截然不同的方法:关系型(SQL)数据库和文档型(NoSQL)数据库。
在本文中,我们将探讨如何与PostgreSQL(通过libpqxx库)和MongoDB(通过官方C++驱动mongo-cxx-driver)协同工作。您将学习如何配置连接、执行CRUD操作以及处理错误。
1. PostgreSQL与C++:关系型方法
PostgreSQL是一款强大的对象关系型数据库管理系统,对事务和复杂查询有出色的支持。对于C++,推荐使用libpqxx库——一个现代、类型安全的libpq封装。
1.1 安装libpqxx
安装方式取决于您的操作系统:
- Ubuntu/Debian:
sudo apt install libpqxx-dev - macOS (Homebrew):
brew install libpqxx - Windows (vcpkg):
vcpkg install libpqxx
1.2 连接与执行查询
我们来看一个连接数据库、创建表并插入数据的最小程序:
#include <iostream>#include <pqxx/pqxx>
int main() { try { // 连接到数据库 pqxx::connection conn("dbname=testdb user=postgres password=secret hostaddr=127.0.0.1 port=5432"); if (conn.is_open()) { std::cout << "Connected to PostgreSQL: " << conn.dbname() << std::endl; }
// 创建事务 pqxx::work txn(conn);
// 创建表 txn.exec("CREATE TABLE IF NOT EXISTS users (" "id SERIAL PRIMARY KEY," "name VARCHAR(100) NOT NULL," "email VARCHAR(255) UNIQUE NOT NULL" ");");
// 插入数据(使用参数化查询以确保安全) txn.exec_params("INSERT INTO users (name, email) VALUES ($1, $2);", "Alice", "alice@example.com");
// 提交事务 txn.commit();
std::cout << "Data inserted successfully." << std::endl;
} catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0;}1.3 读取数据
要检索数据,请使用查询结果的迭代器:
pqxx::work txn(conn);pqxx::result result = txn.exec("SELECT id, name, email FROM users;");
for (auto row : result) { int id = row["id"].as<int>(); std::string name = row["name"].as<std::string>(); std::string email = row["email"].as<std::string>(); std::cout << id << ": " << name << " <" << email << ">" << std::endl;}2. MongoDB与C++:文档型方法
MongoDB以BSON(二进制JSON)格式存储数据。对于C++,使用基于libmongoc库构建的官方驱动mongo-cxx-driver。
2.1 安装mongo-cxx-driver
- Ubuntu:
sudo apt install libmongoc-1.0-0 libbson-1.0-0 libmongocxx-dev - macOS:
brew install mongo-cxx-driver - 从源码编译:需要
cmake、libmongoc和libbson。
2.2 连接与CRUD操作
连接到本地MongoDB实例并插入文档的示例:
#include <iostream>#include <bsoncxx/b