====== PostgreSQL with libpq ====== ''libpq'' is the frontend API for PostgreSQL, written in C. Upstream has fantastic [[https://www.postgresql.org/docs/current/static/|documentation]], but the workflows aren't obvious unless you've used other database APIs like PHP's ''PDO'' class or the ''sqlite'' module in Python. This page will outline a few common tasks and how to do them. ===== Linking ===== The ''-lpq'' argument to your compiler should be enough. You should already have PostgreSQL server installed (and/or its headers) to link to the library correctly. ===== Basic Connection ===== Most languages do this the same way: - attempt to connect - check for an "OK" status - wrap the above in some sort of code block - do your business - close the connection With libpq: #include #include #include int main(int argc, char **argv) { // create what we need to connect: the db connection structure and its options PGconn *conn; const char *dbopts; // accept an argument on the command line to pass to Postgres if (argc > 1) { dbopts = argv[1]; } else { dbopts = "dbname = default"; } // 1: attempt to connect conn = PQconnectdb(dbopts); // 2: check for an OK status that is... // 3: wrapped in a code block if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection failed: %s\n", PQerrorMessage(conn)); } else { // 4: do your business printf("Connection successful!\n"); } // 5: close the connection PQfinish(conn); exit(1); } ===== References ===== * [[https://www.postgresql.org/docs/current/static/libpq-example.html|libpq Examples - PostgreSQL Documentation]]