The most basic three types in libpqxx are the connection (which inherits its API from pqxx::connection_base and its setup behaviour from pqxx::connectionpolicy), the transaction (derived from pqxx::transaction_base), and the result (pqxx::result).
They fit together as follows:
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. exec
function to execute queries, which you pass in as simple strings. c_str()
function, or convert it to other types using its as()
and to()
member functions. These are templated on the destination type: myfield.as<int>()
; or myfield.to(myint)
; 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 the transaction (or even the connection) has been closed.
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 tuples 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.