5

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

4

2 回答 2

12

PostgreSQL 中有两种类型的blobBYTEA —和Large 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;
}
于 2012-01-24T23:50:06.577 回答
3

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

以下是如何使用 pqxx 执行此操作的完整示例: How to insert binary data into a PostgreSQL BYTEA column using the C++ libpqxx API?

简而言之,使用 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();
于 2013-04-21T00:10:35.243 回答