diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 0dda180..ad0d42c 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -2961,9 +2961,9 @@ keep_going:						/* We will come back to here until there is
 					char	   *val;
 
 					val = PQgetvalue(res, 0, 0);
+					PQclear(res);
 					if (strncmp(val, "on", 2) == 0)
 					{
-						PQclear(res);
 						restoreErrorMessage(conn, &savedMessage);
 
 						/* Not writable; close connection. */
@@ -2988,7 +2988,10 @@ keep_going:						/* We will come back to here until there is
 						/* No more addresses to try. So we fail. */
 						goto error_return;
 					}
-					PQclear(res);
+					/* We call PQgetResult repeatedly until it returns NULL */
+					while ((res = PQgetResult(conn)) != NULL)
+						PQclear(res);
+
 					termPQExpBuffer(&savedMessage);
 
 					/* We can release the address lists now. */
