在 C++ 中处理数据库:PostgreSQL 和 MongoDB
现代 C++ 应用程序很少能不涉及数据库交互。无论您是在开发高负载服务器、分析系统还是嵌入式软件,掌握关系型 (PostgreSQL) 和文档型 (MongoDB) 数据库管理系统都是一项必备技能。在本文中,我们将通过实际示例来讲解这两种系统的连接、查询执行和错误处理。
1. 环境准备与库的选择
在 C++ 中处理 PostgreSQL 的事实标准库是 libpqxx。对于 MongoDB,官方驱动是 mongocxx (基于 libmongoc)。
安装 libpqxx (Linux / macOS)
# Ubuntu / Debiansudo apt-get install libpqxx-dev
# macOS (Homebrew)brew install libpqxx安装 mongocxx (Linux / macOS)
# 需要预先安装 libmongoc 和 boostsudo apt-get install libmongoc-1.0-0 libbson-1.0 libmongocxx-dev
# macOSbrew install mongo-cxx-driver对于 Windows,请使用 vcpkg 或从官方仓库下载预编译版本。
2. 通过 libpqxx 使用 PostgreSQL
libpqxx 库在 C 驱动 libpq 之上提供了一个便捷的 C++ 接口。主要类包括:connection、work (事务)、result。
连接数据库
#include <iostream>#include <pqxx/pqxx>
int main() { try { // 连接字符串: "dbname=test user=postgres password=secret hostaddr=127.0.0.1 port=5432" pqxx::connection conn("dbname=testdb user=myuser password=mypass hostaddr=localhost"); if (conn.is_open()) { std::cout << "Connected to PostgreSQL: " << conn.dbname() << std::endl; } } catch (const std::exception &e) { std::cerr << "Connection error: " << e.what() << std::endl; return 1; } return 0;}执行查询 (CRUD)
void createTable(pqxx::connection &conn) { 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," "age INT" ")"); txn.commit();}
void insertUser(pqxx::connection &conn, const std::string &name, const std::string &email, int age) { pqxx::work txn(conn); // 使用参数化查询以防止 SQL 注入 txn.exec_params("INSERT INTO users (name, email, age) VALUES ($1, $2, $3)", name, email, age); txn.commit(); std::cout << "User inserted." << std::endl;}
void selectUsers(pqxx::connection &conn) { pqxx::nontransaction txn(conn); pqxx::result result = txn.exec("SELECT id, name, email, age FROM users"); for (auto row : result) { std::cout << "ID: " << row["id"].as<int>() << ", Name: " << row["name"].as<std::string>() << ", Email: " << row["email"].as<std::string>() << ", Age: " << row["age"].as<int>() << std::endl; }}错误处理
所有操作都应包裹在 try-catch 中。libpqxx 会抛出 pqxx::sql_error、pqxx::broken_connection 等类的异常。
3. 通过 mongocxx 使用 MongoDB
mongocxx 驱动使用现代 C++17。主要实体包括:client、database、collection、document (通过 bsoncxx)。
连接并获取集合
#include <ios