Working with Databases in C++: PostgreSQL and MongoDB

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why connect databases to C++



Modern C++ applications rarely function without persistent data storage. Whether it's a game server, telemetry system, or high-load backend — you will need interaction with a DBMS. Two fundamentally different approaches dominate the market: relational (SQL) and document-oriented (NoSQL) databases.



In this article, we will cover how to work with PostgreSQL (via the libpqxx library) and MongoDB (via the official mongo-cxx-driver). You will learn how to set up a connection, perform CRUD operations, and handle errors.



1. PostgreSQL and C++: the relational approach



PostgreSQL is a powerful object-relational DBMS with excellent support for transactions and complex queries. For C++, the recommended library is libpqxx — a modern, type-safe wrapper over libpq.



1.1 Installing libpqxx

Installation depends on your OS:

  • Ubuntu/Debian: sudo apt install libpqxx-dev
  • macOS (Homebrew): brew install libpqxx
  • Windows (vcpkg): vcpkg install libpqxx


1.2 Connecting and executing queries

Consider a minimal program for connecting to a database, creating a table, and inserting data:



#include <iostream>#include <pqxx/pqxx>

int main() { try { // Connecting to the database 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; }

// Creating a transaction pqxx::work txn(conn);

// Creating a table txn.exec("CREATE TABLE IF NOT EXISTS users (" "id SERIAL PRIMARY KEY," "name VARCHAR(100) NOT NULL," "email VARCHAR(255) UNIQUE NOT NULL" ");");

// Inserting data (with parameterization for safety) txn.exec_params("INSERT INTO users (name, email) VALUES ($1, $2);", "Alice", "alice@example.com");

// Committing the transaction 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 Reading data

To retrieve data, use iterators over the query result:



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 and C++: the document-oriented approach



MongoDB stores data in BSON format (binary JSON). For C++, the official driver mongo-cxx-driver is used, built on top of the libmongoc library.



2.1 Installing mongo-cxx-driver

  • Ubuntu: sudo apt install libmongoc-1.0-0 libbson-1.0-0 libmongocxx-dev
  • macOS: brew install mongo-cxx-driver
  • Building from source: Requires cmake, libmongoc, and libbson.


2.2 Connecting and CRUD operations

Example of connecting to a local MongoDB instance and inserting a document:



#include <iostream>#include <bsoncxx/b                

Blogs

Book Recommendations