Working with Databases in C++: PostgreSQL and MongoDB in Practice

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 does a C++ developer need databases?

C++ is one of the most powerful system programming languages. However, even in high-load projects, it is rarely possible to do without data storage. Whether it's a game server, a financial application, or an IoT system — you will need reliable storage. In this article, we will cover two popular approaches: the relational DBMS PostgreSQL and the document-oriented MongoDB. You will learn how to connect them to a C++ project, perform basic operations, and avoid common mistakes.



1. PostgreSQL in C++: The Classic Relational Database

PostgreSQL is a mature, reliable DBMS with excellent support for transactions and complex queries. To work with it from C++, the libpqxx library is most commonly used — the official C++ wrapper over libpq.



Installation and Setup

Install libpqxx via a package manager or build from source:

# Ubuntu/Debiansudo apt-get install libpqxx-dev

# macOS (Homebrew)brew install libpqxx

In CMakeLists.txt add:

find_package(PQXX REQUIRED)target_link_libraries(your_project pqxx::pqxx)


Connecting to the Database and a Simple SELECT

Let's look at a minimal example — retrieving a list of users:

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

int main() { try { // Connection string: "host=... dbname=... user=... password=..." pqxx::connection conn("host=localhost dbname=testdb user=admin password=secret"); pqxx::work txn(conn);

// Execute the query pqxx::result result = txn.exec("SELECT id, name, email FROM users LIMIT 10");

for (auto row : result) { std::cout << "ID: " << row[0].as<int>() << ", Name: " << row[1].as<std::string>() << ", Email: " << row[2].as<std::string>() << std::endl; }

txn.commit(); // Commit the transaction } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0;}

Note: all operations are wrapped in a try-catch block — libpqxx throws exceptions on any failure.



Parameterized Queries (Security)

Never concatenate strings for value substitution — this opens the door to SQL injection. Use prepared statements:

pqxx::work txn(conn);// Preparationconn.prepare("insert_user", "INSERT INTO users (name, email) VALUES ($1, $2)");

// Execution with parameterstxn.exec_prepared("insert_user", "Ivan Petrov", "ivan@example.com");txn.commit();


2. MongoDB in C++: NoSQL Flexibility

MongoDB stores data in BSON format (binary JSON) and is well-suited for tasks where the data schema may change. The official driver for C++ is mongocxx (built on top of mongoc).



Installing the mongocxx Driver

Building from source is the most reliable method. Quick instructions:

# Install dependencies: libmongoc, libbson, cmakegit clone https://github.com/mongodb/mongo-cxx-driver.gitcd mongo-cxx-driver/buildcmake .. -DCMAKE_BUILD_TYPE=Release -DBSONCXX_POLY_USE_MNMLSTC=ONmake -j4sudo make install

In CMakeLists.txt:

find_package(libmongocxx REQUIRED)target_link_libraries(your_project mongocxx::mongocxx)


Connecting and Inserting a Document

#include <iostream>#include <bsoncxx/json.hpp>#include <mongocxx/client.hpp>#include <mongocxx/instance.hpp>#include <mongocxx/uri.hpp>

int main() { // Initialize the driver (once per application) mongocxx::instance inst{};

// Con

Blogs

Book Recommendations