Introduction to Working with Databases in C++
\n\nModern 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\nThe 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\nPostgreSQL in C++: The Relational Approach
\n\nPostgreSQL 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\nInstalling libpqxx
\n\nOn Linux (Ubuntu/Debian), installation is done with a single command:
\n\nsudo apt-get install libpqxx-dev\n\nFor Windows, you can use vcpkg:
\n\nvcpkg install libpqxx\n\nConnecting and Executing a Query
\n\nLet'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\nReading Data (SELECT)
\n\nTo retrieve data, use the result iterator:
\n\npqxx::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\nImportant: Always use parameterized queries to protect against SQL injection:
\n\ntxn.exec_params("INSERT INTO users (name, email) VALUES ($1, $2)",\n "Alexey", "alex@example.com");\n\nMongoDB in C++: The Document-Oriented Approach
\n\nMongoDB is a NoSQL database that stores data in BSON format (binary JSON). For C++, there is an official driver mongocxx.
\n\nInstalling mongocxx
\n\nInstallation on Linux (requires the MongoDB C Driver to be installed first):
\n\nsudo 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\nConnecting and CRUD Operations
\n\nThe following code demonstrates connecting to