Python psycopg2 cursor.fetchall() 返回空列表,但 cursor.rowcount 是 >1 [英] Python psycopg2 cursor.fetchall() returns empty list but cursor.rowcount is > 1

查看:230
本文介绍了Python psycopg2 cursor.fetchall() 返回空列表,但 cursor.rowcount 是 >1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到问题:

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)

它给出以下输出:

[]
11

这意味着 cursor.rowcount 是 11 但 cursor.fetchall() 是空列表.我已经尝试过这样做:

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)

还有这个解决方案:点击看

对此的任何帮助将不胜感激.

Any help regarding this will be appreciated.

编辑:刚刚遇到另一件事,此代码在第一次执行时运行良好.但是再次执行(第二次、第三次、...n 次执行)会产生上述行为.

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.

推荐答案

我也遇到了同样的问题.我想通了,可能是在调试时,我们允许在建立连接后的一些时间#conn = psycopg2.connect(conn_string)#cursor = conn.cursor()

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.

这篇关于Python psycopg2 cursor.fetchall() 返回空列表,但 cursor.rowcount 是 >1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆