Home > Enterprise >  How can I get double(or bytes) data through PQgetvalue in an efficient way?
How can I get double(or bytes) data through PQgetvalue in an efficient way?

Time:02-25

I create a table with 3 columns: int8, double and bytea. When query a row of data, I use PQgetvalue to get each column value in a row. But PQgetvalue return a char*, I have to convert text value to corresponding type, like atoi or strtod etc.

Is there is a more efficient way to get actual data, avoid converting data every time?

CodePudding user response:

There is not much overhead in converting a char * to a number. But you can use binary mode by calling PQexecParams with 1 as the last argument.

To retrieve binary data, you have to use PQgetlength and PQgetisnull to get size and NULLness of the datum. Also, the data will be in the binary format used by the database server, so the representation of a double could be different if both machines have a different hardware architecture (although IEEE is used pretty much everywhere).

CodePudding user response:

Given these functions:

PQgetvalue:

char *PQgetvalue(const PGresult *res,
                 int row_number,
                 int column_number);

memcpy:

#include <string.h>
void *memcpy(void *restrict dest, const void *restrict src, size_t n);

You extract a double like this:

double dest;

memcpy(&dest, PQgetvalue(...), sizeof dest);
  • Related