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

早过忘川 提交于 2021-02-09 07:20:51

问题


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.


回答1:


After trying different solution, I have figured out that the problem described in the question arises when I execute it in "Debugging Mode" in pycharm. But on the other hand if I execute the code in "Run Mode" in pycharm , it returns the right expected output (a list with 11 elements):

[a,b,c,d,e,f,g,h,i,j,k]

Not sure about the exact reason for it but somehow the cursor was breaking somewhere when run in "Debugging Mode". If anyone describes the exact reason, It ll be highly appreciated.



来源:https://stackoverflow.com/questions/46273972/python-psycopg2-cursor-fetchall-returns-empty-list-but-cursor-rowcount-is-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!