如何使用C++ libpqxx API将二进制数据插入PostgreSQL BYTEA列?

Sté*_*ane 10 c++ postgresql libpqxx

我想将一些二进制数据插入到BYTEA列中,但我发现Doxygen输出缺乏详细信息,并且http://pqxx.org/在过去几天内一直处于停顿状态.

我如何将somefile.bin的内容插入带有BYTEA列的表中?

我所拥有的是这些方面:

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();
Run Code Online (Sandbox Code Playgroud)

如果它有所不同,我想hex在PostgreSQL 9.1中使用BYTEA 的新格式.

Sté*_*ane 10

弄清楚了.下面是一个示例,说明如何将一堆二进制对象插入表中:

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();
Run Code Online (Sandbox Code Playgroud)

以下是如何从数据库中取出二进制数据:

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();
    ...
}
Run Code Online (Sandbox Code Playgroud)