将数值绑定到准备好的sql的正确方法

Correct way to bind numeric values to prepared sql

本文关键字:sql 方法 准备好 绑定      更新时间:2023-10-16

我没有使用过libpq fe,(postgresql-9.1.3)

PGresult * pg_res;
char * sql = "INSERT INTO tbGroups (Group_UID, Full_Name, User_UID) VALUES ($1, $2, $3);";
int group_uid = 11;
int user_uid = 1;
const char * name = "TEST1";
const char * values[3] = {(const char *) &group_uid, name, (const char *) &user_uid};
int lengths[3] = {sizeof(group_uid), strlen(name), sizeof(user_uid)};
int format[3] = {1, 1, 1};
pg_res = PQprepare(conn, "insert_tbgroups", sql, 3, NULL);
PQclear(pg_res);
pg_res = PQexecPrepared(conn, "insert_tbgroups", 3, values, lengths, format, 1);
PQclear(pg_res);

有效,但结果是:

rcpdv=#从tbGroups中选择group_uid、full_name、user_uid;group_uid|full_name|user_uid-----------+---------------+----------184549376 |测试1 | 16777216(1行)

在没有param_types的情况下,将数值绑定到准备好的sql的正确方法是什么?

PostgreSQL期望数据通过网络连接。因此,您必须将数字数据转换为网络格式(big-endian)。我通常使用ntohl()函数,在您的情况下举一个粗略的例子:

int format[3] = {1, 1, 1};
for (i = 0; i < 3; ++i) {
    format[i] = ntohl(format[i]);
}