检测是否从psycopg2游标获取?

2024-04-20 13:01:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我执行以下命令。

insert into hello (username) values ('me')

我跑得像

cursor.fetchall()

我得到以下错误

psycopg2.ProgrammingError: no results to fetch

如何在不检查查询是“insert”还是“select”的情况下检测是否调用fetchall()?

谢谢。


Tags: tono命令hello错误usernamecursorresults
3条回答

看看这个属性:

cur.description

执行查询后,如果未返回行,则将其设置为“无”,否则将包含数据-例如:

(Column(name='id', type_code=20, display_size=None, internal_size=8, precision=None, scale=None, null_ok=None),)

捕获异常并不理想,因为可能存在重写真正异常的情况。

问题是,结果证明没有的是cur.fetchone()的结果 所以停止循环的方法是:

cursor.execute("SELECT * from rep_usd")
output = cursor.fetchone()
while output is not None:
    print(output)
    output = DBCursor.fetchone()

cursor.description永远不会是None!

使用cur.description接受的答案不再解决问题。cur.statusmessage可以是一个解决方案。这将返回SELECT 0INSERT 0 1。一个简单的字符串操作可以帮助确定最后一个查询。

相关问题 更多 >