# C++

Connect to ParticleDB from C++, run parameterized queries, handle transactions and errors.

Source: https://particledb.ai/sdks/cpp/

Use the configured address for your client. See [connection addresses](/installation/ports/) and [security](/guides/security/). The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.

Use [libpqxx](https://github.com/jtv/libpqxx), the C++ client for PostgreSQL, over the PostgreSQL
wire (port 5432). You can also call [libpq](/sdks/c/) directly.

## Install libpqxx

```bash
# macOS (Homebrew)
brew install libpqxx

# Debian/Ubuntu
sudo apt-get install libpqxx-dev
```

The example below uses the libpqxx 7.10 API (`pqxx::params`, `query<>()`).

## 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](/connectivity/tls/#authentication).

```cpp
#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:

```bash
c++ -std=c++17 -o demo demo.cpp $(pkg-config --cflags --libs libpqxx libpq)
./demo
```

```
1 alice
2 bob
```

`tx.exec(sql, pqxx::params{...})` sends values as bind parameters, so you do not need to
escape them.

## Next steps

- [C](/sdks/c/). libpq directly
- [SQL Reference](/sql/overview/). SQL syntax and examples
- [SQL client connections](/connectivity/pg-wire/). connection settings and compatibility
