[Libpqxx-general] insert using tablewriter

tans at email.arizona.edu tans at email.arizona.edu
Wed Sep 30 18:11:00 UTC 2009


I am new to libpqxx and PostgreSQL.  I have the following pseudo code function:

bool insertEmployee(Connection &con, Employee &obj)
{
  const char* stmt = "INSERT INTO employee (id, name, salary) VALUES (%d, '%s',
%.10f)";

  if(!con.execute(stmt, obj.getId(), obj.getName(), obj.getSalary()))
     return false;
  return true;
}

What is a good way to implement the above code using libpqxx?
Looking through the libpqxx api, I think the following would work:

bool insertEmployee(pqxx::connection &con, Employee &obj)
{
  const char *const CData[][2] =
  {
     {"id", obj.getId()},  //integer
     {"name", obj.getName()},  //string
     {"salary", obj.getSalary()},  //float
     {0,0}
  };

  try {
    pqxx::work Xaction(con, "Insert Employee");
    pqxx::tablewriter W(Xaction, "employee");

    for (int i=0; CData[i][0]; ++i)
      W.insert(&CData[i][0], &CData[i][2]);

    W.complete();
    T.commit();
  }
  catch (const exception &e) {
    std::cerr << "Exception: " << e.what() << std::endl;
    return false;
  }

  return true;
}

Is the above correct; is there a better way?

Thanks



More information about the Libpqxx-general mailing list