Python MySQLdb:查询参数作为命名字典
作者:互联网
我想将查询参数传递给MySQLdb的cursor.execute()方法作为命名字典,以便它们从SQL注入中转义.
你能解释为什么这会给KeyError:
>>> c.execute('select id from users where username=%(user)s', {'user':'bob',})
KeyError: 'user'
MySQLdb手册http://mysql-python.sourceforge.net/MySQLdb.html说:
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 forconn.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.
解决方法:
您粘贴的文档中的行可能会回答您的问题:
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,mysql-python 来源: https://codeday.me/bug/20191001/1838995.html