如何从删除查询中捕获/获取结果以确定删除的行数



我正在尝试了解如何使用psycopg2在Python代码中捕获从delete命令中删除的记录数。通常,在PostgreSql中发出删除命令后,会显示删除的行数(即DELETE 8,其中8表示删除的行数来(。我想在每次删除后记录这个计数,以便向调用方报告删除的行数,而无需在delete命令之前制作单独的SELECT count(*)

考虑这个功能:

def qexe(conn, query, fetch_type):
cursor = conn.cursor()
cursor.execute(query)
if fetch_type != None:
if fetch_type == 'fetchall':
query_result = cursor.fetchall()
return query_result
elif fetch_type == 'fetchone':
query_result = cursor.fetchone()
return query_result
else:
raise Exception(f"Invalid arg fetch_type: {fetch_type}")
cursor.close()

在运行以下每一个之后,我不断地得到错误:psycopg2.ProgrammingError: no results to fetch:

qq = """DELETE FROM INV WHERE ITEM_ID = '{}';"""
item='123abc'
resp0 = qexe(conn, qq.format(item), 'fetchone')
resp1 = qexe(conn, qq.format(item), 'fetchall')

您可以使用RETURNING,这样您就可以从光标中取回"某物":

qq = """DELETE FROM INV WHERE ITEM_ID = '{}' RETURNING ITEM_ID"""
resp0 = qexe(conn, qq.format(item), 'fetchone')