Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created November 9, 2018 08:39
Show Gist options
  • Save fearofcode/7516c9b7b18922386148195be5660329 to your computer and use it in GitHub Desktop.
Save fearofcode/7516c9b7b18922386148195be5660329 to your computer and use it in GitHub Desktop.
working libpqxx example
#include <iostream>
#include <chrono>
#include <pqxx/pqxx>
int main(int, char *argv[])
{
pqxx::connection c("dbname=arete user=postgres password=postgres");
{
pqxx::work txn(c);
pqxx::result r = txn.exec(
"create table if not exists employee(id serial primary key, name text, salary integer)");
txn.commit();
}
c.prepare("insert_employee", "insert into employee(name, salary) values($1, $2)");
auto start = std::chrono::high_resolution_clock::now();
pqxx::work txn(c);
txn.exec_prepared0("insert_employee", "Warren", 12345);
pqxx::result r = txn.exec(
"SELECT id "
"FROM Employee "
"WHERE name =" + txn.quote("Warren") + " order by id desc limit 1");
if (r.size() != 1)
{
std::cerr
<< "Expected 1 employee with name 'Warren', "
<< "but found " << r.size() << std::endl;
return 1;
}
int employee_id = r[0][0].as<int>();
std::cout << "Updating employee #" << employee_id << std::endl;
txn.exec(
"UPDATE EMPLOYEE "
"SET salary = salary + 1 "
"WHERE id = " + txn.quote(employee_id));
txn.commit();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
std::cout << "Done in " << elapsed_seconds.count() << 'ms\n';
std::cin.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment