在破解 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 中实现一个循环,但我宁愿避免这种情况。
啊,是的,性能也很重要。