Python MySQLdb:将参数作为命名字典进行查询 [英] Python MySQLdb: Query parameters as a named dictionary
问题描述
我想将查询参数作为命名字典传递给MySQLdb
的cursor.execute()
方法,以使它们从SQL注入中被转义.
I want to pass query parameters to cursor.execute()
method of MySQLdb
as a named dictionary, such that they are escaped from SQL injection.
您能解释一下为什么给出KeyError
的原因吗?
Can you explain why this gives KeyError
:
>>> c.execute('select id from users where username=%(user)s', {'user':'bob',})
KeyError: 'user'
MySQLdb手册 http://mysql-python.sourceforge.net/MySQLdb.html说:
MySQLdb manual http://mysql-python.sourceforge.net/MySQLdb.html says:
paramstyle
paramstyle
字符串常量,说明接口期望的参数标记格式的类型.设置为'format'
= ANSI C printf格式代码,例如'...WHERE name=%s'
.如果将映射对象用于conn.execute()
,则该接口实际上使用'pyformat'
= Python扩展格式代码,例如'...WHERE name=%(name)s'
.但是,API目前不允许在paramstyle中指定一种以上的样式.
String constant stating the type of parameter marker formatting expected by the interface. Set to 'format'
= ANSI C printf format codes, e.g. '...WHERE name=%s'
. If a mapping object is used for conn.execute()
, then the interface actually uses 'pyformat'
= Python extended format codes, e.g. '...WHERE name=%(name)s'
. However, the API does not presently allow the specification of more than one style in paramstyle.
推荐答案
文档中粘贴内容之后的行可能会回答您的问题:
The line in the documentation following what you pasted may answer your question:
参数占位符只能用于插入列值. 他们 不能用于SQL的其他部分,例如表名,语句等.
Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.
这篇关于Python MySQLdb:将参数作为命名字典进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!