WikiStart: complete-example.cxx

File complete-example.cxx, 1.5 KB (added by jtv, 2 months ago)
Line 
1/// Sample libpqxx program, in C++11.
2
3#include <iostream>
4#include <pqxx/pqxx>
5
6/// Query employees from database.  Return result.
7pqxx::result query()
8{
9  pqxx::connection c{"dbname=company user=accounting"};
10  pqxx::work txn{c};
11
12  pqxx::result r = txn.exec("SELECT name, salary FROM Employee");
13  for (auto row: r)
14    std::cout
15      // Address column by name.  Use c_str() to get C-style string.
16      << row["name"].c_str()
17      << " makes "
18      // Address column by zero-based index.  Use as<int>() to parse as int.
19      << row[1].as<int>()
20      << "."
21      << std::endl;
22
23  // Not really needed, since we made no changes, but good habit to be
24  // explicit about when the transaction is done.
25  txn.commit();
26
27  // Connection object goes out of scope here.  It closes automatically.
28  return r;
29}
30
31
32/// Query employees from database, print results.
33int main(int, char *argv[])
34{
35  try
36  {
37    pqxx::result r = query();
38
39    // Results can be accessed and iterated again.  Even after the connection
40    // has been closed.
41    for (auto row: r)
42    {
43      std::cout << "Row: ";
44      // Iterate over fields in a row.
45      for (auto field: row) std::cout << field.c_str() << " ";
46      std::cout << std::endl;
47  }
48  catch (const std::exception &e)
49  {
50    std::cerr << "Error: " << e.what() << std::endl;
51    return 1;
52  }
53  catch (const pqxx::sql_error &e)
54  {
55    std::cerr << "SQL error: " << e.what() << std::endl;
56    std::cerr << "Query was: " << e.query() << std::endl;
57    return 2;
58  }
59}