Connecting to PostgreSQL with C++

In this article, we will introduce how to connect to a PostgreSQL cluster using C++ and some of the possible actions that you can perform on a PostgreSQL database.

The easiest way to set up a C++ client for PostgreSQL is using the libpqxx interface. First, install the libpqxx package onto your local machine. Refer to the official documentation for more information.

Connecting to a cluster

 

where <node ip address> is the ip address of your master node, and <password> is the password for the icpostgresql user. You can find this information on the Connection Info page of your cluster.

This will connect you to the postgres database on your cluster, which is created when your cluster is initially provisioned. You can then process SQL statements by creating a  transaction object operating on your connection.

You can now use the transaction’s exec, query_value, and stream functions to execute SQL statements. Make sure to call the transaction’s commit function after submitting a SQL statement to make its work final. If you don’t call this, your changes to the database will not be persistent.

Creating a table

Populating a table with rows

Committing the transaction

Querying a table

The data from a SQL query is stored in a pqxx::result object, which acts as a standard container of rows: pqxx::row.

Further Reading

The examples above only give basic use cases for libpqxx.  For more information please see the official libpqxx API documentation.

By Instaclustr Support
Need Support?
Experiencing difficulties on the website or console?
Already have an account?
Need help with your cluster?
Contact Support
Why sign up?
To experience the ease of creating and managing clusters via the Instaclustr Console
Spin up a cluster in minutes