psycopg2 准备删除语句

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 无法将参数转换为字符串。

有什么方法可以使用 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 构建查询作为回答

实际上,如果仔细构建,分辨率是很容易的。

miscellaneous goodies of psycopg2中有一个函数execute_values

虽然 psycopg2 给出的所有示例都处理插入,因为函数基本上将参数列表转换为 VALUES 列表,如果对 delete 的调用格式如下:

qry = "delete from table where (col1, col2) in (%s)"

来电:

execute_values(cur=cur, qry=qry, argslist=<list of value tuples>)

将使删除完全按照要求执行。