是否可以使用 Python 标准库(例如版本 2.5)执行参数化的 MS-SQL 查询?
虽然我现在使用的特定数据不是用户生成的,并且在我通常的验证例程中将在其生命周期内进行清理,但我想了解如何进行基本的插入、选择等操作。 SQL查询同时保护自己免受SQL注入攻击,仅供将来参考。 我宁愿学习如何通过参数化查询以“正确”的方式做事。
清理总是好的,但我正在将我可怜的智力与经验丰富的黑客进行比较。 手动转义意味着我可能会忽略一些事情,因为黑名单不如白名单那么强大。 为了补充说明,我并不是说使用 (%s)
表示法作为参数传递来构建可能名为 sqlstatement
的字符串。 我认为我需要知道的神奇词之一是“约束力”。
我还希望避免使用 Python 标准库之外的任何东西。
如果相关的话,相关应用程序需要 Microsoft SQL 2005。 我正在使用 ActiveState Python 以及模块 dbi 和 odbc。 由于这是其他人的数据库,因此存储过程已不再适用。
While the particular data I'm working with right now will not be user-generated, and will be sanitized within an inch of its life during my usual validation routines, I would like to learn how to do your basic INSERT, SELECT, etc. SQL queries while protecting myself against SQL injection attacks, just for future reference. I'd rather learn how to do things the "right" way, through parameterized queries.
Sanitization is always nice, but I am pitting my pitiful intellect against that of seasoned hackers. Manually escaping means I am probably overlooking things, since blacklists are not as robust as whitelists. For additional clarification, I do not mean using the (%s)
notation to pass as a parameter for building a string possibly named sqlstatement
. I think one of the magic words I need to know is "binding."
I am also hoping to avoid anything outside of the Python Standard Library.
The application in question requires Microsoft SQL 2005, if that is relevant. I am using ActiveState Python and the modules dbi and odbc. Since this is Someone Else's Database, stored procedures are out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PEP 249 (DB API 2.0) 定义了 5 个参数样式,PyMSSQL 使用 paramstyle == pyformat。 但虽然它看起来像字符串插值,但它实际上是绑定。
注意绑定之间的区别:
和插值(这是不应该完成的方式):
另请参阅http://wiki.python.org/moin/DbApiFaq
你运气不好。Python 中唯一内置的 RDBMS 驱动程序是 SQLite。
PEP 249 (DB API 2.0) defines 5 paramstyles, PyMSSQL uses paramstyle == pyformat. But although it looks like string interpolation, it is actually binding.
Note difference between binding:
and interpolating (this is how it should NOT be done):
See also http://wiki.python.org/moin/DbApiFaq
You're out of luck here. The only RDBMS driver that comes built-in in Python is SQLite.
尝试 pyodbc
但如果您想让事情变得非常简单(加上大量强大的功能),看看 sqlalchemy (顺便说一句,它使用 pyodbc 作为 mssql 的默认“驱动程序”)
Try pyodbc
But if you want to have things really easy (plus tons of powerful features), take a look at sqlalchemy (which by the way uses pyodbc as the default "driver" for mssql)