Since this question is the top search result for inserting a BYTEA via libpqxx, here's another way to do it using a parameterized query, which is more appropriate if performing only a single insert. The accepted answer of using pqxx::connection::prepare
causes the prepared query to exist for the entire lifetime of the connection. If the connection will be long-lasting and a prepared query is no longer needed, it should probably be deleted by calling pqxx::connection::unprepare
.
2024 update, using libpqxx 7.9.0:
// Assuming pre-existing pqxx::connection c, void * bin_data, size_t bin_size...
pqxx::work txn(c);
txn.exec_params0("INSERT INTO mytable(name, binfile) VALUES ($1, $2)", name, pqxx::binary_cast(bin_data, bin_size));
txn.commit();
In this solution, the pqxx::binary_cast
helper is used to pass binary data held in a C-style pointer to data of know length (in its two argument version) or C++ STL containers such as std::vector<uint8_t>
(in its single argument version). This is just a cast, so there is no unnecessary copying of the data.
Original answer, written for libpqxx 5.0.0:
// Assuming pre-existing pqxx::connection c, void * bin_data, size_t bin_size...
pqxx::work txn(c);
pqxx::result res = txn.parameterized("INSERT INTO mytable(name, binfile) VALUES ($1, $2)")
(name)
(pqxx::binarystring(bin_data, bin_size))
.exec();
txn.commit();
Note that the parameters should not be escaped with the quote
or esc
methods. The pqxx::binary_cast
helper also wasn't available until libpqxx 7.6.0, so this approach copies the data into a pqxx::binarystring
object before passing it to the query, which is an inefficiency that would best be avoided if possible.
n
element to insert with one query (performance issue). I'm working on a solution (with pqxx 5.0.1). – Espinoza