如何使用python优雅地参数化sqldelete语句?

2024-05-08 00:10:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要删除的用户ID列表: 用户id是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上使用Python3.6.5。 我希望查询按如下方式执行

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

Tags: 代码用户infromidformatlenwhere
1条回答
网友
1楼 · 发布于 2024-05-08 00:10:11

根据您正在使用的数据库和数据库接口库,使用库的参数传递机制可能更容易。例如,对于PostgreSQL和psycopg2,类似的方法应该可以工作:

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

(未经测试就输入,因此可能充满了琐碎的错误)。你知道吗

这也将消除SQL注入的风险。你知道吗

相关问题 更多 >