首页 > 解决方案 > 如何使用python优雅地参数化SQL DELETE语句?

问题描述

我有一个要删除的 user_ids 列表: user_ids 是str类型。

users = ['user1', 'user2', 'user3']

目前我正在用这些代码删除它们

query_delete = 'delete from users where user_id in ({});'.format('?, '*len(users))
# delete from users where user_id in (?, ?, ?, );

query_delete.replace(", )", ")")
# delete from users where user_id in (?, ?, ?);

cursor.execute(query_delete, users)

我认为使用.format('?, '*len(users))参数化查询不够优雅。
有没有更好的方法让代码更优雅、更易读?

编辑
我在 CentOS 7 和 MySQL 8 上使用 python 3.6.5。我希望查询执行为

delete from users where user_id in ('user1', 'user2', 'user3');

标签: python

解决方案


根据您使用的数据库和数据库接口库,使用库的参数传递机制可能更容易。例如,对于 PostgreSQL 和 psycopg2,这样的事情应该可以工作:

users = [ 'user1', 'user2', 'user3' ]
cursor.execute("DELETE FROM user WHERE user_id = ANY (%(u)s)",
               { 'u': users })

(没有测试就打字,所以可能充满了琐碎的错误)。

这也将消除 SQL 注入的风险。


推荐阅读