使用远程机器的libpq在PostgreSQL中插入二进制大对象(BLOB)

你能给出一个使用libpq从远程机器在PostgreSQL数据库中插入二进制数据的例子。 我的第二个问题是:是否有任何其他API比使用C ++的libpq更有效。 谢谢

PostgreSQL中有两种类型的blobBYTEALarge Objects 。 我建议不要使用大对象,因为你不能将它们连接到表。

对于BYTEA,你可以在libpq中使用这样的东西:

 PGresult* put_data_to_tablename( PGconn* conn, int32_t id, int data_size, const char* const data ) { PGresult* result; const uint32_t id_big_endian = htonl((uint32_t)id); const char* const paramValues[] = { &id_big_endian, data }; const int nParams = sizeof(paramValues) / sizeof(paramValues[0]); const int paramLenghts[] = { sizeof(id_big_endian), data_size }; const int paramFormats[] = { 1, 1 }; /* binary */ const int resultFormat = 0; /* text */ result = PQexecParams( conn, "insert into tablename (id, data) values ($1::integer, $2::bytea)", nParams, NULL, /* Types of parameters, unused as casts will define types */ paramValues, paramLenghts, paramFormats, resultFormat ); return result; } 

使用libpqxx是C ++的方法,而libpq是C API。

以下是如何使用pqxx执行此操作的完整示例: 如何使用C ++ libpqxx API将二进制数据插入PostgreSQL BYTEA列?

简而言之,使用libpqxx的相关C ++行看起来像这样:

 void * bin_data = ...; // obviously do what you need to get the binary data... size_t bin_size = ...; // ...and the size of the binary data pqxx::binarystring bin( bin_data, bin_size ); pqxx::result r = work.prepared( "test" )( bin ).exec(); work.commit();