我想用python在postgres中進行批量洗掉,我的where子句有多個列以獲取正確的記錄。
例如。 對于一條記錄,我這樣運行 delete products where company_id='123' and product_id=1;
我試著對多條記錄使用這個方法,但得到了這個錯誤
該查詢包含一個以上的'%s'占位符
。query = delete products where company_id='%s'/span> and product_id=%s;
values =[(1,2), (3,4) ]
psycopg2.extras.execute_values(self.cursor, delete_query, values)
uj5u.com熱心網友回復:
我看到你分享的片段有幾個問題
delete from <tablame> where ...你可以執行多個查詢來洗掉記錄,或者你可以傳遞一個值串列來與復合欄位(company_id, product_id) & 使用execute_values
假設company_id是文本& 你的值串列包含字串
多個查詢:
stmt = "delete from products where company_id = %s and product_id = %s"
cur.execute('begin')
try:
for cid, pid in values:
cur.execute(sttmt, (cid, pid))
cur.execute('commit')
# 做其他事情。
except:
cur.execute('rollback')
# do other things to handle this exception: cur.execute('rollback)
一個查詢 execute_values
from postgresql.extras import execute_values
stmt = "delete from products where (company_id, product_id) IN (%s)"/span>
execute_values(cur, stmt, values)
psycopg2.extras 檔案頁包含很多有用的函式,包括execute_values
uj5u.com熱心網友回復:
你正在向每個%s發送一個元組,而不是一個單一的值。
這就是它的使用方法:
參考文獻。 https://www.psycopg.org/docs/extras.html?highlight=uuid
>>> execute_values(cur,
... ""UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1)
... where test.id = data.id""。
... [(1, 20), (4, 50) ])
因此,在你的案例中,它需要類似于這樣的東西。請看他們是如何參考資料的。
... ""DELETE products USING (VALUES %s) AS data (companyId, productId)
... WHERE company_id = data.companyId and product_id = data.productId ""。
... [(1, 20), (4, 50) ])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/307989.html
標籤:
