Python MySQLdb:将参数作为命名字典进行查询 [英] Python MySQLdb: Query parameters as a named dictionary

查看:119
本文介绍了Python MySQLdb:将参数作为命名字典进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将查询参数作为命名字典传递给MySQLdbcursor.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆