【问题标题】:cur execute repeating parametercur 执行重复参数
【发布时间】:2017-06-26 12:24:05
【问题描述】:

我正在 python 中执行 SQL 查询。表示重复参数的正确方法是什么? 示例:我有

cur.execute("""select * from TableA where field1= '{}' and field2 = '{}'""".format(a,a))

这里的“a”和“a”是一样的。我需要在参数列表中重复它还是有什么方法只给它一次。

【问题讨论】:

  • 您使用哪个库来执行此操作? MySQL数据库?
  • 是的,我正在为此使用 mysqldb。
  • 不要使用字符串插值 (.format()),因为存在 SQL 注入的风险。而是做cur.execute("select * from TableA where field1= '%s' and field2 = '%s'", a, a)。另一种方法是清理你的参数safe_a = MySQLdb.escape_string(a),然后使用format(),但这对我来说似乎很冗长。
  • 好的,谢谢,但这并不能回答如何表示重复参数的问题,即,而不是在参数列表中给出两次“a”。
  • 如果你真的想使用format()而不是重复你的参数format()可以用一个数字来表示参数的位置:cur.execute("select * from TableA where field1 = '{0}' and field2 = '{0}'".format(MySQLdb.escape_string(a)))

标签: python sql mysql-python


【解决方案1】:

在括号内放一个数字来引用位置参数。

safe_a = MySQLdb.escape_string(a) # protect against sql-injection!!!
cur.execute("select * from TableA where field1 = '{0}' and field2 = '{0}'".format(safe_a))

【讨论】:

  • 我也经常使用这种方式,我认为这是最简单易读的方式。
猜你喜欢
  • 1970-01-01
  • 2019-02-07
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2018-10-01
相关资源
最近更新 更多