我想将查询参数作为命名字典传递给cursor.execute()
方法,以便它们从 SQL 注入中逃脱。MySQLdb
你能解释为什么这会给出KeyError
:
>>> c.execute('select id from users where username=%(user)s', {'user':'bob',})
KeyError: 'user'
MySQLdb 手册http://mysql-python.sourceforge.net/MySQLdb.html说:
参数样式
字符串常量,说明接口期望的参数标记格式的类型。设置为
'format'
= ANSI C printf 格式代码,例如'...WHERE name=%s'
. 如果映射对象用于conn.execute()
,则接口实际使用'pyformat'
= Python 扩展格式代码,例如'...WHERE name=%(name)s'
。但是,API 目前不允许在 paramstyle 中指定一种以上的样式。