wiki:CodeExamples

Code examples

We have a few non-trivial example programs to help you going.

These programs are not tested automatically as part of the test suite, so they may have fallen out of data with later libpqxx changes. If they fail to compile or work, please report the problem—see the New Ticket link at the top of the page.

Example type conversions

Sometimes you'll want to convert between database fields and C++ types for which libpqxx does not include a standard conversion. The conversions are extensible, so anyone can add conversions by specializing the pqxx::string_traits for a new C++ type, and libpqxx will then know how to convert that type. You may find the conversion you need here.

Date/time: boost::posix_time::ptime

Johannes Lochmann provides this conversion implementation for Boost ptime fields:

#include <string>
#include <sstream>

#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

namespace pqxx
{
template<> struct PQXX_LIBEXPORT string_traits<boost::posix_time::ptime>
{
  static const char *name() { return "boost::posix_time::ptime"; }
  static bool has_null() { return false; }
  static bool is_null(const boost::posix_time::ptime &) { return false; }
  static boost::posix_time::ptime null()
  {
    return boost::posix_time::ptime();
  }
  static void from_string(const char Str[], boost::posix_time::ptime &Obj)
  {
    Obj = boost::posix_time::time_from_string(std::string(Str));
  }
  static PGSTD::string to_string(const boost::posix_time::ptime &Obj)
  {
    std::stringstream ss;
    ss << Obj;
    return ss.str();
  }
};
}

(An open question is: will locale conversions cause any problems?)

UUIDs: boost::uuids::uuid

Another one from Johannes Lochmann, this time for Boost's UUID type.

#include <string>
#include <sstream>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>

namespace pqxx
{
template<> struct PQXX_LIBEXPORT string_traits<boost::uuids::uuid>
{
  static const char *name() { return "boost::uuids::uuid"; }
  static bool has_null() { return false; }
  static bool is_null(const boost::uuids::uuid &) { return false; }
  static boost::uuids::uuid null()
  {
    internal::throw_null_conversion(name());
    boost::uuids::nil_generator gen;
    boost::uuids::uuid u = gen();
    return u;
  }
  static void from_string(const char Str[], boost::uuids::uuid &Obj)
  {
    std::stringstream ss;
    ss << std::string(Str);
    ss >> Obj;
  }
  static PGSTD::string to_string(const boost::uuids::uuid &Obj)
  {
    std::stringstream ss;
    ss << Obj;
    return ss.str();
  }
};
}
Last modified 5 years ago Last modified on Jul 24, 2012, 12:10:03 PM