Getting started

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:

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.

 #include <iostream>
 #include <pqxx/pqxx>

 int main()
 {
   try
   {
     pqxx::connection c;
     pqxx::work w(c);
     pqxx::result r = w.exec("SELECT 1");
     w.commit();

     std::cout << r[0][0].as<int>() << std::endl;
   }
   catch (const std::exception &e)
   {
     std::cerr << e.what() << std::endl;
     return 1;
   }
 }

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.

 #include <iostream>
 #include <pqxx/pqxx>

 int main(int argc, char *argv[])
 {
   if (!argv[1])
   {
     std::cerr << "Give me a string!" << std::endl;
     return 1;
   }
   try
   {
     pqxx::connection c;
     pqxx::work w(c);
     pqxx::result r = w.exec("SELECT " + w.quote(argv[1]));
     w.commit();

     std::cout << r[0][0].c_str() << std::endl;
   }
   catch (const std::exception &e)
   {
     std::cerr << e.what() << std::endl;
     return 1;
   }
 }

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.


Generated on Mon Feb 15 18:22:46 2010 for libpqxx by  doxygen 1.5.5