Search code examples
postgresqllibpqxx

postgresql libpqxx Several queries as one transaction


Is it possible to execute one transaction contains several queries, for example insert smth in table1 and insert smth in table2? How I can implement this? I use libpqxx to interact the database and expect an answer relating to that. Thank you.


Solution

  • pqxx::work is a default transaction type. Use multiple exec() method before commit() to run multiple queries in one transaction:

    using namespace pqxx;
    ...
      connection c("dbname=test user=postgres hostaddr=127.0.0.1");
      work w(c);
      w.exec("create table test_xx (id int primary key)");
      w.exec("insert into test_xx values (1)");
      w.commit();
    ...