如何使用libpq使用Postgresql的二进制结果

时间:2019-01-23 14:43:40

标签: c++ postgresql libpq

我正在尝试将PQexecPrepare的二进制结果绑定到诸如int,float之类的变量...我不知道该怎么做。我的目的是:使用长度和二进制值,我可以将结果指向int或float的指针。通常,我将使用此函数通过BindResult(T *,int col)函数绑定任何类型的变量。你可以帮帮我吗?

#include <iostream>
#include "libpq-fe.h"

/*

CREATE TABLE fruits(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price FLOAT);
INSERT INTO fruits VALUES(1,'apple',1.9);
INSERT INTO fruits VALUES(2,'banana',1.1);
INSERT INTO fruits VALUES(3,'pear',2.2);
INSERT INTO fruits VALUES(4,'orange',3.2);

*/
void exit_nicely(PGconn *conn)
{
    PQfinish(conn);
    exit(1);
}


int main(int argc, char **argv)
{
    PGconn     *conn;
    PGresult   *res;

    conn =  PQsetdbLogin("127.0.0.1",
                     "5432",
                     NULL,
                     NULL,
                     "testdb",
                     "postgres",
                     "password");
    /* Check to see that the backend connection was successfully made */
    if (PQstatus(conn) != CONNECTION_OK)
    {
        fprintf(stderr, "Connection to database '%s' failed.\n", PQdb(conn));
        fprintf(stderr, "%s", PQerrorMessage(conn));
        exit_nicely(conn);
    }

    const char *paramValues[1];
    int         paramLengths[1];
    int         paramFormats[1];
    paramValues[0] = "1";
    res = PQexecParams(conn,
                   "SELECT * FROM FRUITS WHERE ID>$1",
                   1,       /* one param */
                   NULL,    /* let the backend deduce param type */
                   paramValues,
                   NULL,
                   NULL,
                   1); //binary result

    if(PQresultStatus(res) != PGRES_TUPLES_OK)
        exit_nicely(conn);
    int *iID;
    float *fPrice ;
    for( int row = 0 ; row <  PQntuples(res) ; ++row )
    {

    int length= PQfsize(res,col);
    char *id=PQgetvalue(res,row,0);
    char *price=PQgetvalue(res,row,2);
    //how to bind the value to iID and fPrice?
    //iID 
    //fPrice 

    }
    PQclear(res);
    PQfinish(conn);
    return 0;
}

0 个答案:

没有答案