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 libpq, PostgreSQL’s C client library, over the SQL client interface (port 5432). It gives you bind parameters, transactions, and TLS.
Install libpq
Section titled “Install libpq”# macOS (Homebrew)brew install libpq
# Debian/Ubuntusudo apt-get install libpq-dev
# Fedora/RHELsudo dnf install libpq-develQuick 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 <stdio.h>#include <stdlib.h>#include <libpq-fe.h>
static void die(PGconn *conn, PGresult *res) { fprintf(stderr, "error: %s", PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(1);}
int main(void) { PGconn *conn = PQconnectdb( "host=localhost port=5432 dbname=particledb user=postgres password=secret"); if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "connect failed: %s", PQerrorMessage(conn)); PQfinish(conn); return 1; }
PGresult *res = PQexec(conn, "CREATE TABLE demo (id BIGINT PRIMARY KEY, name TEXT)"); if (PQresultStatus(res) != PGRES_COMMAND_OK) die(conn, res); PQclear(res);
const char *params[2] = {"1", "Alice"}; res = PQexecParams(conn, "INSERT INTO demo (id, name) VALUES ($1, $2)", 2, NULL, params, NULL, NULL, 0); if (PQresultStatus(res) != PGRES_COMMAND_OK) die(conn, res); printf("inserted %s\n", PQcmdTuples(res)); PQclear(res);
const char *id[1] = {"1"}; res = PQexecParams(conn, "SELECT id, name FROM demo WHERE id = $1", 1, NULL, id, NULL, NULL, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) die(conn, res); for (int i = 0; i < PQntuples(res); i++) printf("id=%s name=%s\n", PQgetvalue(res, i, 0), PQgetvalue(res, i, 1)); PQclear(res);
PQfinish(conn); return 0;}Compile and run:
cc -o demo demo.c $(pkg-config --cflags --libs libpq)./demoinserted 1id=1 name=AliceWith Homebrew’s keg-only libpq, first point pkg-config at it:
export PKG_CONFIG_PATH="$(brew --prefix libpq)/lib/pkgconfig".
PQexecParams sends values as bind parameters, so you do not need to escape them. Use
PQexec with BEGIN / COMMIT / ROLLBACK for transactions.
Next steps
Section titled “Next steps”- C++. libpqxx, the C++ wrapper around libpq
- SQL Reference. SQL syntax and examples
- SQL client connections. connection settings and compatibility
This site uses Google Analytics cookies to count visits. Privacy · License