【发布时间】:2013-07-23 11:44:53
【问题描述】:
在破解 MySQL 绑定的 python 代码时,我更喜欢使用命名占位符,但似乎我无法使用 IN 子句来恰到好处。一个例子:
con = MySQLdb.connect(db='test', user='test')
cur = con.cursor()
三个过于简单的例子:
# (#1) works fine, but I want placeholders.
cur.execute( """ update test
set i = 999
where SNO in (1, 2) """)
# (#2) works fine too, but still not enough placeholders.
cur.execute( """ update test
set i = %(i)s
where SNO in (1, 2) """, {'i' : 999})
# (#3) works, but did not pass the beauty check...
cur.execute( """ update test
set i = %(i)s
where SNO in ( %(a)s, %(b)s ) """, {'i' : 99,
'a' : 1,
'b' : 2})
这是我真正想要的,但它失败了:操作数应该包含 1 列
# (#4) This one fails with: _mysql_exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
cur.execute( """ update test
set i = %(i)s
where SNO in ( %(foo)s ) """, {'i' : 999,
'foo' : [1, 2]})
显然我需要更多的魔法。将问题转移到应用程序中很容易,在 python 中实现一个循环,但我宁愿避免这样做。
是的,性能也很重要。
【问题讨论】:
-
",".join(['1', '2'])而不是 [1,2] 怎么样? (适用于普通的 python 占位符) -
出于安全原因,我认为最好使用光标占位符
-
是的,但是,作为一种解决方法,您可以在查询参数上调用
mysqldb.escapestring。
标签: python mysql python-2.7