Working with Databases in C++: PostgreSQL and MongoDB for Beginners

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 to Working with Databases in C++

\n\n

Modern applications rarely do without data storage. C++ is a powerful systems programming language that is well-suited for high-load projects working with databases. In this article, we will look at how to connect to two popular DBMSs — the relational PostgreSQL and the document-oriented MongoDB — and perform basic operations (CRUD).

\n\n

The material is designed for beginners: you will learn which libraries are needed, how to install them, and see ready-made code examples. After reading, you will be able to independently integrate C++ with any of these databases.

\n\n

PostgreSQL in C++: The Relational Approach

\n\n

PostgreSQL is one of the most reliable open-source relational DBMSs. To work with it from C++, the libpqxx library is used — an official wrapper over the C library libpq.

\n\n

Installing libpqxx

\n\n

On Linux (Ubuntu/Debian), installation is done with a single command:

\n\n
sudo apt-get install libpqxx-dev
\n\n

For Windows, you can use vcpkg:

\n\n
vcpkg install libpqxx
\n\n

Connecting and Executing a Query

\n\n

Let's look at a simple example: connecting to a database, creating a table, and inserting data.

\n\n
#include <iostream>\n#include <pqxx/pqxx>\n\nint main() {\n    try {\n        // Connecting to the database (replace parameters with your own)\n        pqxx::connection conn("dbname=testdb user=postgres password=secret hostaddr=127.0.0.1 port=5432");\n        \n        if (conn.is_open()) {\n            std::cout << "Connection to PostgreSQL successful!" << std::endl;\n        }\n\n        // Creating a transaction\n        pqxx::work txn(conn);\n\n        // Creating a table\n        txn.exec("CREATE TABLE IF NOT EXISTS users ("\n                 "id SERIAL PRIMARY KEY, "\n                 "name VARCHAR(100) NOT NULL, "\n                 "email VARCHAR(100) UNIQUE NOT NULL)");\n\n        // Inserting data\n        txn.exec("INSERT INTO users (name, email) VALUES "\n                 "('Ivan Petrov', 'ivan@example.com'), "\n                 "('Maria Smirnova', 'maria@example.com')");\n\n        // Committing the transaction\n        txn.commit();\n        std::cout << "Data added successfully!" << std::endl;\n\n    } catch (const std::exception &e) {\n        std::cerr << "Error: " << e.what() << std::endl;\n        return 1;\n    }\n    return 0;\n}
\n\n

Reading Data (SELECT)

\n\n

To retrieve data, use the result iterator:

\n\n
pqxx::work txn(conn);\npqxx::result result = txn.exec("SELECT id, name, email FROM users");\n\nfor (const auto &row : result) {\n    int id = row["id"].as<int>();\n    std::string name = row["name"].as<std::string>();\n    std::string email = row["email"].as<std::string>();\n    std::cout << id << " | " << name << " | " << email << std::endl;\n}
\n\n

Important: Always use parameterized queries to protect against SQL injection:

\n\n
txn.exec_params("INSERT INTO users (name, email) VALUES ($1, $2)",\n                "Alexey", "alex@example.com");
\n\n

MongoDB in C++: The Document-Oriented Approach

\n\n

MongoDB is a NoSQL database that stores data in BSON format (binary JSON). For C++, there is an official driver mongocxx.

\n\n

Installing mongocxx

\n\n

Installation on Linux (requires the MongoDB C Driver to be installed first):

\n\n
sudo apt-get install libmongoc-dev libbson-dev\ngit clone https://github.com/mongodb/mongo-cxx-driver.git\ncd mongo-cxx-driver\nmkdir build && cd build\ncmake .. -DCMAKE_BUILD_TYPE=Release -DBSONCXX_POLY_USE_MNMLSTC=ON\nmake -j4\nsudo make install
\n\n

Connecting and CRUD Operations

\n\n

The following code demonstrates connecting to

Blogs

Book Recommendations