From: Tom Lane <tgl@sss.pgh.pa.us>
To: Gao Yanxiao <553216793@qq.com>
Cc: pgsql-bugs@postgresql.org
Subject: Re: BUG? select count(*) from table don't get value via PQgetvalue() function in libpq(C)
Date: Sat, 18 Feb 2017 12:58:28 -0500
Message-ID: <27458.1487440708@sss.pgh.pa.us> (raw)
In-Reply-To: <000001d28a00$a3549c30$e9fdd490$@qq.com>
References: <000001d28a00$a3549c30$e9fdd490$@qq.com>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-bugs>
"Gao Yanxiao" <553216793@qq.com> writes:
> res = PQexecParams(pgconn, "select count(*) from chat_connstate", 0, NULL, NULL, NULL, NULL, 1);
So you asked for binary-format results ...
> So, I use PQgetvalue() function get the value, like this:
> Int result = *((int*)PQgetvalue(res, 0, 0));
> Or
> Long result = *((long*)PQgetvalue(res, 0, 0);
The first of those is certainly not going to work, and depending on what
platform you're on the second won't either, because it's only extracting
the first 32 bits of the 64-bit result of count().
The other problem you've got here is that the result is coming off the
wire in big-endian byte order, and you're not doing anything to convert
that into native byte order (which more than likely is little-endian).
The reason you're seeing zeroes is that the high 32 bits of the result
are zeroes.
Personally, I would not bother with binary format unless I anticipated
processing enormous volumes of data; it's just too error-prone.
Better to use text and apply strtol() or whatever.
If you really must do it in binary format, here's the way pq_getmsgint64
reads a 64-bit big-endian value:
int64 result;
uint32 h32;
uint32 l32;
pq_copymsgbytes(msg, (char *) &h32, 4);
pq_copymsgbytes(msg, (char *) &l32, 4);
h32 = ntohl(h32);
l32 = ntohl(l32);
result = h32;
result <<= 32;
result |= l32;
which is pretty tedious, but there's no standard 64-bit version
of ntohl/htonl, so we have to swap each half separately.
regards, tom lane
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-bugs@postgresql.org
Cc: tgl@sss.pgh.pa.us, 553216793@qq.com
Subject: Re: BUG? select count(*) from table don't get value via PQgetvalue() function in libpq(C)
In-Reply-To: <27458.1487440708@sss.pgh.pa.us>
References: <000001d28a00$a3549c30$e9fdd490$@qq.com> <27458.1487440708@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox