python - 如何使用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');
解决方案
根据您使用的数据库和数据库接口库,使用库的参数传递机制可能更容易。例如,对于 PostgreSQL 和 psycopg2,这样的事情应该可以工作:
users = [ 'user1', 'user2', 'user3' ]
cursor.execute("DELETE FROM user WHERE user_id = ANY (%(u)s)",
{ 'u': users })
(没有测试就打字,所以可能充满了琐碎的错误)。
这也将消除 SQL 注入的风险。
推荐阅读
- python - 如何获得矩阵中3个元素的最小总和
- sql - 无法使用 stuff 将 100000 行导出到变量
- java - 如何为更多不同的构建进行应用设计?
- scala - 如何在 sbt 库中为 1.0.0-M10 及以上版本设置依赖关系
- python - 根据多个条件将列的值填充到数据框的新列
- random - 如何从一个大组中创建固定数量的主题的子组?
- spring - 休息调用不检索存在的子类实体
- android - 页面未完全渲染并在 appium 中不断闪烁,但在手动完成时正确渲染
- asp.net-mvc - 将数据从文件 .cs 或 cshtml 文件的值发送到 js MVC
- windows - 如何在 Windows 上抑制控制台窗口?