Question: I'd like to insert some binary data into a BYTEA column, but I find the Doxygen output is lacking in details, and <http://pqxx.org/> has been down for the past few days.

How would I go about inserting the contents of somefile.bin into a table with a BYTEA column?

What I have is along these lines:

```
pqxx::work work( conn );
work.exec( "CREATE TABLE test ( name varchar(20), data BYTEA )" );
work.exec( "INSERT INTO test( name, data ) VALUES ( 'foo', <insert filename.bin here> )" );
work.commit();

```

If it makes a difference, I'd like to use the new `hex` format for BYTEA available in PostgreSQL 9.1.

Answer: 
Figured it out. Here is an example showing how to insert a bunch of binary objects into a table:

```
pqxx::connection conn( ... );
conn.prepare( "test", "INSERT INTO mytable( name, binfile ) VALUES ($1, $2)" );
pqxx::work work( conn );
for ( ... )
{
    std::string name = "foo";
    void * bin_data = ...; // obviously do what you need to get the binary data...
    size_t bin_size = 123; // ...and the size of the binary data

    pqxx::binarystring blob( bin_data, bin_size );
    pqxx::result r = work.prepared( "test" )( name )( blob ).exec();
}
work.commit();

```

Here is how to get the binary data back out of the database:

```
pqxx::result result = work.exec( "SELECT * FROM mytable" );
for ( const auto &row : result )
{
    pqxx::binarystring blob( row["binfile"] );
    void * ptr = blob.data();
    size_t len = blob.size();
    ...
}

```
I've come up with a flexible solution using binary data inside `std::string`. 

I propose this new solution because current answers are old (2013) and I was looking for a multi insert query using pqxx 5.0.1. 

With the solution bellow you have the flexibility to use a `for loop` to append multiple binary data in a single insert query. 

```
CustomStruct data = .... ; // have some binary data

// initialise connection and declare worker
pqxx::connection conn = new pqxx::connection(...);    
pqxx::work w(conn); 

// prepare query
string query += "INSERT INTO table (bytea_field) VALUES ("
// convert your data in a binary string. 
pqxx::binarystring blob((void *)&(data), data.size());
// avoid null character to bug your query string. 
query += "'"+w.esc_raw(blob.str())+"');";

//execute query
pqxx::result rows = w.exec(query);

```

When we want to retrieve data from the database you should have the scope of your datatype (`CustomStruct` for instance) and you should be able to cast it back in the binary format of your choice.

```
// assuming worker and connection are declared and initialized.
string query = "SELECT bytea_field FROM table;";
pqxx::result rows = w.exec(query);
for(pqxx::result::iterator col = rows.begin(); col != rows.end(); ++col)
{
    pqxx::binarystring blob(col[0]);
    CustomStruct *data = (CustomStruct*) blob.data();
    ...
}

```

This was tested with `pqxx 5.0.1`, `c++11` and `postgresSQL 9.5.8`