我正在尝试使用以下稍微简单的代码将一些整数插入到 Postgres 表中。
#include <libpq-fe.h>
#include <stdio.h>
#include <stdint.h>
int main() {
int64_t i = 0;
PGconn * connection = PQconnectdb( "dbname='babyfood'" );
if( !connection || PQstatus( connection ) != CONNECTION_OK )
return 1;
printf( "Number: " );
scanf( "%d", &i );
char * params[1];
int param_lengths[1];
int param_formats[1];
param_lengths[0] = sizeof( i );
param_formats[0] = 1;
params[0] = (char*)&i;
PGresult * res = PQexecParams( connection,
"INSERT INTO intlist VALUES ( $1::int8 )",
1,
NULL,
params,
param_lengths,
param_formats,
0 );
printf( "%s\n", PQresultErrorMessage( res ) );
PQclear( res );
PQfinish( connection );
return 0;
}
我得到以下结果:
Number: 55 ERROR: integer out of range
Number: 1 ERROR: integer out of range
我很确定 int64_t 在任何健全的平台上总是适合 8 字节整数。我做错了什么?
最佳答案
代替:
params[0] = (char*)&i;
你应该使用:
#include <endian.h>
/* ... */
int64_t const i_big_endian = htobe64(i);
params[0] = (char*)&i_big_endian;
htobe64
函数将在小端上切换字节顺序,而在大端上什么都不做。
放弃你的 flip_endian
函数,因为它会使你的程序与大端/双端计算机不兼容,如 PowerPC、Alpha、摩托罗拉、SPARC、IA64 等。即使你的程序不兼容expect to be run on them 这是一种糟糕的风格,缓慢且容易出错。
关于c - 将整数作为二进制发送时出现 PostgreSQL libpq "Integer out of range"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1302301/