libpqxx
libpqxx is the official-style C++ client for PostgreSQL. It wraps libpq with RAII connections, transactions, and streams. You write SQL; you do not get an ORM.
Detailed Explanation
Postgres is a server. libpq is the C client. libpqxx is the C++ layer you should use if you talk to Postgres from C++: pqxx::connection, pqxx::work (a transaction), exec, exec_params, stream.
A connection is one TCP (or socket) session. It is not thread-safe. The usual design is a pool of connections (or one per request thread). Construction takes a connection string (dbname=app user=app host=localhost). Failure throws pqxx::broken_connection or a setup error.
pqxx::work txn(conn); starts a transaction. txn.exec_params("select name from t where id=$1", id); binds safely. txn.commit(); persists. If the work object dies without commit, it rolls back. That is RAII transactions. pqxx::read_transaction is read-only. pqxx::nontransaction is autocommit (each statement its own transaction).
Results: pqxx::result r = txn.exec(...); iterate rows, row["name"].as<std::string>(). NULL becomes an exception on .as<T>() unless you use get<T>() optional forms or check is_null.
exec_params is the prepared-ish API for one-shot parameterized SQL. conn.prepare("q", "select ... $1"); txn.exec_prepared("q", id); is a named prepared statement on the connection.
Binary data, arrays, and composite types have dedicated support. Prefer text for simple types. Time stamps: use std::chrono mappings in recent libpqxx, or text ISO-8601 if you want fewer surprises.
Never build SQL with +. $1 placeholders plus exec_params are the rule. Identifier quoting (txn.quote_name) is separate from value binding.
libpqxx 7 is C++17. Check your distro's package; the API shifted from older pqxx::result patterns.
Code Examples
#include <pqxx/pqxx>
#include <iostream>
#include <string>
int main() {
try {
pqxx::connection c("dbname=app user=app");
pqxx::work txn(c);
txn.exec0("create table if not exists t(id int, name text)");
txn.exec_params("insert into t(id, name) values ($1, $2)", 1, "ada");
auto r = txn.exec_params("select name from t where id=$1", 1);
std::cout << r[0]["name"].as<std::string>() << '\n';
txn.commit();
} catch (const pqxx::failure&) {
return 1; // no server in this example environment
}
}Common Gotchas
Using a connection from two threads
libpq forbids it. Pool.
`.as<T>()` on NULL
throws. Check null or use optional helpers.
Forgetting `commit()`
the destructor rolls back. Your insert vanished. That is the feature; it surprises people who expected autocommit.
`$1` is Postgres bind syntax
do not put quotes around `$1`.