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

C++ 使用远程计算机上的libpq在PostgreSQL中插入二进制大对象(BLOB),c++,c,database,postgresql,libpq,C++,C,Database,Postgresql,Libpq,您能否给出一个使用libpq从远程机器在PostgreSQL数据库中插入二进制数据的示例。 我的第二个问题是:有没有比C++更有效的API? 谢谢PostgreSQL中有两种类型的blob-BYTEA和大型对象。我建议不要使用大型对象,因为不能将它们连接到表中 对于BYTEA,您可以在libpq中使用如下内容: PGresult* put_data_to_tablename( PGconn* conn, int32_t id, int data_size, const char*

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

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

对于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;
}

使用LIPPQXX是C++的方式,而LIPPQ是C API。 以下是如何使用pqxx执行此操作的完整示例:

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

值得注意的是,LIPPQXX有老化问题,不,它不是“官方”PostgreSQL C++的API,因为它在网站上声明。