我試圖了解如何使用 psycopg2 捕獲從 Python 代碼中的洗掉命令中洗掉的記錄數。通常在 PostgreSql 中發出洗掉命令后,會顯示洗掉的行數(即DELETE 8
,其中 8 表示已洗掉的行數)。我想在每次洗掉后記錄這個計數,以便向呼叫者報告洗掉的行數,而無需SELECT count(*)
在 DELETE 命令之前單獨創建。
考慮這個函式:
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')
uj5u.com熱心網友回復:
您可以使用RETURNING
,因此您將能夠取回可以從游標中獲取的“某些東西”:
qq = """DELETE FROM INV WHERE ITEM_ID = '{}' RETURNING ITEM_ID"""
resp0 = qexe(conn, qq.format(item), 'fetchone')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507965.html
標籤:python-3.x 心理咨询师2