【发布时间】: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