Python psycopg2 cursor.fetchall() returns empty list but cursor.rowcount is > 1

Viewed 4298

I am getting an issue here:

conn = psycopg2.connect(conn_string)
cursor = conn.cursor()

sql = """
    SELECT DISTINCT (tenor_years) 
    FROM bond_pnl 
    WHERE country = '%s'
""" % country

cursor.execute(sql)
print(cursor.fetchall())
print(cursor.rowcount)

It gives the following output:

[]
11

which means that cursor.rowcount is 11 but cursor.fetchall() is empty list. I have already tried doing this:

conn.set_session(readonly=True, autocommit=True)

and this solution as well :Click to see

Any help regarding this will be appreciated.

EDIT: Just came across another thing, this code when executed first time, works fine. But executing it again(second, third, ...n execution) gives the above behavior.

2 Answers

I also faced the same issue. I figured out that, Might be while debugging, we are allowing some fraction of time after connection has been made #conn = psycopg2.connect(conn_string) #cursor = conn.cursor()

By the time we hit the execution button for the next line (which contains the query), database is timed out and it is returning empty list.

If anyone has any other logic for why this is happening please do share.

Related