我尝试使用 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/