C++
Use the configured address for your client. See connection addresses and security. The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.
Use libpqxx, the C++ client for PostgreSQL, over the PostgreSQL wire (port 5432). You can also call libpq directly.
Install libpqxx
Section titled “Install libpqxx”# macOS (Homebrew)brew install libpqxx
# Debian/Ubuntusudo apt-get install libpqxx-devThe example below uses the libpqxx 7.10 API (pqxx::params, query<>()).
Quick start
Section titled “Quick start”The example connects as postgres with the password secret, for a server started with
particledb start --auth-method scram-sha-256 --pg-password secret. With the server’s default
--auth-method password, add sslmode=require to the connection string; see
TLS and authentication.
#include <iostream>#include <pqxx/pqxx>
int main() { pqxx::connection conn{ "host=localhost port=5432 dbname=particledb user=postgres password=secret"};
{ pqxx::nontransaction tx{conn}; tx.exec("CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT)"); tx.commit(); }
{ pqxx::work tx{conn}; tx.exec("INSERT INTO users (id, name) VALUES ($1, $2)", pqxx::params{1, "alice"}); tx.exec("INSERT INTO users (id, name) VALUES ($1, $2)", pqxx::params{2, "bob"}); tx.commit(); // without commit(), the transaction rolls back when tx goes out of scope }
pqxx::read_transaction rtx{conn}; for (auto [id, name] : rtx.query<long long, std::string>( "SELECT id, name FROM users ORDER BY id")) { std::cout << id << " " << name << "\n"; }}Compile and run:
c++ -std=c++17 -o demo demo.cpp $(pkg-config --cflags --libs libpqxx libpq)./demo1 alice2 bobtx.exec(sql, pqxx::params{...}) sends values as bind parameters, so you do not need to
escape them.
Next steps
Section titled “Next steps”- C. libpq directly
- SQL Reference. SQL syntax and examples
- SQL client connections. connection settings and compatibility
This site uses Google Analytics cookies to count visits. Privacy · License