使用setSingleRowMode libpq时,行号0超出范围0 ..- 1

时间:2014-08-01 01:03:18

标签: postgresql libpq

我试图使用PQsetSingleRowMode逐个检索行。结果集是正常的,除了返回最后3行,行号0超出范围0 ..- 1

这是我的主要功能:

int main(){
/* The code to create connection to the database is fine, so I skipped it */

PQsetnonblocking(conn,1);
  const char *DML_statement="select * from itsdb.PvKeyword";
  int status = PQsendQuery(conn,DML_statement);
  int isSingleMode=PQsetSingleRowMode(conn);
  res = PQgetResult(conn);
  cout << "print out 1 if it is single mode: " << isSingleMode;
  char* field1;
  char* field2;
  char* field3;

  while (PQgetResult(conn)!= NULL || PQresultStatus(res)!=PGRES_TUPLES_OK || PQresultStatus(res)==PGRES_SINGLE_TUPLE)
  {
        res = PQgetResult(conn);
        field1 = PQgetvalue(res,0,0);
        field2 = PQgetvalue(res,0,1);
        field3 = PQgetvalue(res,0,2);
        cout << field1 << "," << field2 << "," << field3 << endl;
        PQclear(res);
  }

结果集:

david,3,male
natalie,1,female
daniel,1,,female
row number 0 is out of range 0..-1
row number 0 is out of range 0..-1
row number 0 is out of range 0..-1

我将它改为do / while并且它有效。

char* field1;
char* field2;
char* field3;

do {
  if (PQresultStatus(res)==PGRES_TUPLES_OK)
     break;
  res = PQgetResult(conn);
  field1 = PQgetvalue(res,0,0);
  field2 = PQgetvalue(res,0,1);
  field3 = PQgetvalue(res,0,2);
  cout << field1 << "," << field2 << "," << field3 << endl;
  PQclear(res);
} while (PQgetResult(conn)!= NULL || PQresultStatus(res)==PGRES_SINGLE_TUPLE)

1 个答案:

答案 0 :(得分:1)

您应该在while循环中使用以下条件:

while (res != nullptr && PQresultStatus(res) == PGRES_SINGLE_TUPLE)

缺少PQresultStatus(res) == PGRES_SINGLE_TUPLE条件导致在最后一个有效行之后检索一个额外的行。