经过长时间的查阅文档、讨论区和邮件列表却毫无进展,我想问一下:如何使用 libpq 的 PQexecParams(.)
对我的数据进行编码以便进行二进制传输?
简单变量按大端序排列即可:
PGconn *conn;
PGresult *res;
char *paramValues[1];
int paramLengths[1];
int paramFormats[1];
conn = PQconnectdb(CONNINFO);
// -- (1) -- send a float value
float val_f = 0.12345678901234567890; // float precision: ~7 decimal digits
// alloc some memory & write float (in big endian) into
paramValues[0] = (char *) malloc(sizeof(val_f));
*((uint32_t*) paramValues[0]) = htobe32(*((uint32_t*) &val_f)); // host to big endian
paramLengths[0] = sizeof(val_f);
paramFormats[0] = 1; // binary
res = PQexecParams(conn, "SELECT $1::real ;", //
1, // number parameters
NULL, // let the backend deduce param type
paramValues, //
paramLengths, //
paramFormats, //
0); // return text
printf("sent float: %s \n", PQgetvalue(res, 0, 0));
// --> sent float: 0.123457
而像这样也适用于double、int等类型...
但数组呢?
float vals_f[] = {1.23, 9.87};
// alloc some memory
paramValues[0] = (char *) malloc(sizeof(float) * 2);
// ???? paramValues[0] = ??????
paramLengths[0] = sizeof(float) * 2;
paramFormats[0] = 1; // binary
res = PQexecParams(conn, "SELECT $1::real[] ;", //
1, // number parameters
NULL, // let the backend deduce param type
paramValues, //
paramLengths, //
paramFormats, //
0); // return text
printf("sent float array: %s \n", PQgetvalue(res, 0, 0));
有没有将数组数据以PostgreSQL二进制格式传输的工作示例?
backend/utils/adt/
中的代码对我不大有帮助(除了我现在知道有一个ARRAYTYPE,但不知道如何使用它):-(我只需要一个函数
char* to_PQbin(float [] input, int length)
, 以便传递给 paramValues[.]
...谢谢, Tebas
附言:转换简单变量的建议方式是什么(而不是我的
htobe32(.)
)?