Python MySQLdb: Query parameters as a named dictionary [closed]

回眸只為那壹抹淺笑 提交于 2019-12-03 18:03:47

问题


I want to pass query parameters to cursor.execute() method of MySQLdb as a named dictionary, such that they are escaped from SQL injection.

Can you explain why this gives KeyError:

>>> c.execute('select id from users where username=%(user)s', {'user':'bob',})
KeyError: 'user'

MySQLdb manual http://mysql-python.sourceforge.net/MySQLdb.html says:

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.


回答1:


The line in the documentation following what you pasted may answer your question:

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.




回答2:


MySQLdb allows dicts as query parameters. This response shows all different ways to do it. You only need to provide a secuence as such parameter (tuple, dict...) as second parameter to "execute". DO NOT format your query as only one parameter to "execute" method or you will be likely exposed to SQL injection attacks. See:

"SELECT * FROM users WHERE username = '%s'" % (user)

Think what would happen if:

user = "peter;DROP TABLE users"   :_(

The other way is secured as it lets the MySQLdb library to handle the necessary checking.

I do not know what is wrong, because your query works fine for me:

# Connect to db
# Open a cursor
stmt = "SELECT * FROM users WHERE username = %(user)s"
cursor.execute(stmt, {"user": "bob"})
user = cursor.fetchone()
print user

{'username': 'bob', 'alias': 'bobby', 'avatar': 'default', 'fullname': 'bob'}

Can you give us more info?



来源:https://stackoverflow.com/questions/12831408/python-mysqldb-query-parameters-as-a-named-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!