我正在尝试创建一个可以访问 PostgreSQL 数据库的程序。问题是我不断得到一个
警告:已经有一个事务在进行中
消息,程序很快退出。我是否需要在需要时关闭并重新打开连接,或者我可以解决问题并在整个程序中重复使用相同的连接?
int i = 0;
std::string spassw = "";
std::string suname = "";
theconn = NULL;
// Make a connection to the database
theconn = PQconnectdb("user=postgres password=changeme dbname=database hostaddr=127.0.0.1 port=5432");
// Check to see that the backend connection was successfully made
if ( PQstatus(theconn) != CONNECTION_OK ) {
std::cout << "Connection to database failed.\nPress any key to continue.\n";
PQfinish(theconn);
getchar();
exit(1);
}
PGresult *res = PQexec(theconn, "BEGIN");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
printf("BEGIN command failed");
PQclear(res);
PQfinish(theconn);
std::cout << "Goodbye.\n";
getchar();
exit(1);
}
// Clear result
PQclear(res);
res = PQexec(theconn, "DECLARE emprec CURSOR FOR select * from dbtable");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
printf("DECLARE CURSOR failed\n");
PQclear(res);
PQfinish(theconn);
std::cout << "Goodbye.\n";
getchar();
exit(1);
}
PQclear(res);
res = PQexec(theconn, "FETCH ALL in emprec");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
printf("FETCH ALL failed");
PQclear(res);
PQfinish(theconn);
std::cout << "Goodbye.\n";
getchar();
exit(1);
}
for ( i = 0; i < PQntuples(res); i++ ) {
std::string suname = PQgetvalue( res, i, 0 );
std::string spassw = PQgetvalue( res, i, 1 );
if( pname == suname && pword == spassw ) {
res = PQexec( theconn, "COMMIT");
PQclear(res);
res = PQexec(theconn, "CLOSE emprec" );
PQclear(res);
// End the transaction
res = PQexec(theconn, "END");
// Clear result
PQclear(res);
return true;
}
}
res = PQexec( theconn, "COMMIT");
PQclear(res);
res = PQexec(theconn, "CLOSE emprec");
PQclear(res);
// End the transaction
res = PQexec(theconn, "END");
// Clear result
PQclear(res);
return false;
}