检测是否从 psycopg2 游标中获取? [英] Detect whether to fetch from psycopg2 cursor or not?

查看:67
本文介绍了检测是否从 psycopg2 游标中获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我执行以下命令.

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

我就这样跑

cursor.fetchall()

我收到以下错误

psycopg2.ProgrammingError: no results to fetch

如何在不检查查询是插入"还是选择"的情况下检测是否调用 fetchall()?

How can I detect whether to call fetchall() or not without checking the query is "insert" or "select"?

谢谢.

推荐答案

看这个属性:

cur.description

执行查询后,如果没有返回行,它将被设置为 None,否则将包含数据 - 例如:

After you have executed your query, it will be set to None if no rows were returned, or will contain data otherwise - for example:

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

捕获异常并不理想,因为在某些情况下您可能会覆盖真正的异常.

Catching exceptions is not ideal because there may be a case where you're overriding a genuine exception.

这篇关于检测是否从 psycopg2 游标中获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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