[英]psycopg2 execute_values DELETE statement returning syntax error
[英]psycopg2 prepared delete statement
我正在努力生成刪除查詢,其中查詢的參數實際上是一組值。
所以我需要刪除參數是一對值的行,例如:
delete from table where col1 = %s and col2 = %s
可以在 Python 中執行,例如:
cur = conn.cursor()
cur.execute(query, (col1_value, col2_value))
現在我想運行一個查詢:
delete from table where (col1, col2) in ( (col1_value1, col2_value1), (col1_value2, col2_value2) );
我可以生成查詢和值並執行確切的 SQL 但我不能完全生成准備好的語句。
我試過了:
delete from table where (col1, col2) in %s
和
delete from table where (col1, col2) in (%s)
但是當我嘗試執行時:
cur.execute(query, list_of_col_value_tuples)
或者
cur.execute(query, tuple_of_col_value_tuples)
我收到一個異常,表明 psycopg2 無法將 arguments 轉換為字符串。
有沒有辦法使用 psycopg2 執行這樣的查詢?
您可以在查詢中動態添加%s
占位符:
cur = con.cursor()
query = "delete from table where (role, username) in (%s)"
options = [('admin', 'foo'), ('user', 'bar')]
placeholders = '%s,' * len(options)
query = query % placeholders[:-1] # remove last comma
print(query)
print(cur.mogrify(query, options).decode('utf-8'))
出去:
delete from table where (role, user) in (%s,%s)
delete from table where (role, user) in (('admin', 'foo'),('user', 'bar'))
或者,使用psycopg2.sql
構建查詢作為回答那里。
實際上,如果仔細構造,分辨率是很容易的。
在psycopg2 的雜項中有一個 function execute_values
。
雖然 psycopg2 給出的所有示例都處理插入,因為 function 基本上將 arguments 列表轉換為VALUES
列表,如果刪除調用的格式如下:
qry = "delete from table where (col1, col2) in (%s)"
來電:
execute_values(cur=cur, qry=qry, argslist=<list of value tuples>)
將使刪除完全按照要求執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.