postgresql - 使用 setSingleRowMode libpq 时返回行号 0 超出范围 0..-1

标签 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)

最佳答案

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

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

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

关于postgresql - 使用 setSingleRowMode libpq 时返回行号 0 超出范围 0..-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071360/

相关文章:

C++ 如何将 MIT Kerberos 与 libpq 一起使用?

Ruby 脚本卡在错误的 PG 连接调用上

postgresql - pgAdmin 和 PostgreSQL : can't connect to server

python - SQLAlchemy DateTime 时区

postgresql - 来自 PostgreSQL 存储过程的多个结果集

python - 通过 OID 转换为类型?

java - android postgresql数据库连接错误

postgresql - 如果不同步,如何重置 postgres 的主键索引

sql - 如何在 libpq 中使用 PQexecParams?

sql - libpq 如何传递批量数据