【发布时间】:2013-04-21 08:10:35
【问题描述】:
您能否举一个使用 libpq 从远程机器将二进制数据插入 PostgreSQL 数据库的示例。 我的第二个问题是:是否有任何其他 API 比使用 C++ 的 libpq 更有效。 谢谢
【问题讨论】:
标签: c++ c database postgresql libpq
您能否举一个使用 libpq 从远程机器将二进制数据插入 PostgreSQL 数据库的示例。 我的第二个问题是:是否有任何其他 API 比使用 C++ 的 libpq 更有效。 谢谢
【问题讨论】:
标签: c++ c database postgresql libpq
PostgreSQL中有两种类型的blob——BYTEA和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;
}
【讨论】:
使用 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();
【讨论】: