Python MySQLdb: Query parameters as a named dictionary

MySQLdb allows dictionary as query parameters. This response shows all different ways to do it. You only need to provide a sequence 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 is equal to a string like:

peter';DROP TABLE users;SELECT * from users where ''='

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?


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.