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

Insert Binary Large Object (BLOB) in PostgreSQL using libpq from remote machine

本文关键字:插入 计算机 二进制大对象 BLOB PostgreSQL libpq      更新时间:2023-10-16

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

PostgreSQL 中有 2 种类型的 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 执行此操作的完整示例:如何使用 libpqxx API 将二进制数据插入 PostgreSQL BYTEA 列C++?

简而言之,使用 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();