libpqxx
The C++ client library for PostgreSQL
|
The most basic three types in libpqxx are the connection, the transaction, and the result.
They fit together as follows:
You create a transaction object (see Transaction classes) operating on that connection. You'll usually want the pqxx::work variety.
Once you're done you call the transaction's commit function to make its work final. If you don't call this, the work will be rolled back when the transaction object is destroyed.
Most of the exec functions return a pqxx::result object, which acts as a standard container of rows: pqxx::row.
Each row in a result, in turn, acts as a container of fields: pqxx::field. See Accessing results and result rows for more about results, rows, and fields.
Here's a very basic example. It connects to the default database (you'll need to have one set up), queries it for a very simple result, converts it to an int, and prints it out. It also contains some basic error handling.
This prints the number 1. Notice that you can keep the result object around after you've closed the transaction or even the connection. There are situations where you can't do it, but generally it's fine. If you're interested: you can install your own callbacks for receiving error messages from the database, and in that case you'll have to keep the connection object alive. But otherwise, it's nice to be able to "fire and forget" your connection and deal with the data.
You can also convert an entire row to a series of C++-side types in one go, using the as
member function on the row:
Here's a slightly more complicated example. It takes an argument from the command line and retrieves a string with that value. The interesting part is that it uses the escaping-and-quoting function quote to embed this string value in SQL safely. It also reads the result field's value as a plain C-style string using its c_str function.
You can find more about converting field values to native types, or converting values to strings for use with libpqxx, under String conversion. More about getting to the rows and fields of a result is under Accessing results and result rows.
If you want to handle exceptions thrown by libpqxx in more detail, for example to print the SQL contents of a query that failed, see Exception classes.