python 的轻量级 DBAL

发布于 2024-11-28 21:12:21 字数 192 浏览 9 评论 0原文

有人可以向我推荐一些最适合我的要求的 python DBAL 库吗?我想直接编写sql语句,大部分逻辑将在db存储过程(postgresql)中,所以我只需要调用db过程,向它们传递参数并获取结果。该库应该帮助我引用(防止 sql 注入)。 我玩过sqlalchemy,但我认为直接将sql语句写入engine.execute方法时没有引用助手。

谢谢

can somebody please recomend me some python DBAL library that will best suit my requirements. I would like to write my sql statements directly, most of the logics will be in db stored procedures (postgresql), so I only need to invoke db procedures, pass arguments to them and fetch the results. The library should help me with quoting (preventing sql inject).
I played with sqlalchemy, but i think that there is no quoting helper when writing sql statement directly to engine.execute method.

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埖埖迣鎅 2024-12-05 21:12:21

您应该更深入地了解 sqlalchemy;它在引用占位符方面做得很好:

>>> engine = sqlalchemy.create_engine("sqlite:///:memory:")
>>> engine.execute("select ?", 5).fetchall()
[(5,)]
>>> engine.execute("select ?", "; drop table users; --").fetchall()
[(u'; drop table users; --',)]

You should have given sqlalchemy a deeper look; It does a fine job of quoting placeholders:

>>> engine = sqlalchemy.create_engine("sqlite:///:memory:")
>>> engine.execute("select ?", 5).fetchall()
[(5,)]
>>> engine.execute("select ?", "; drop table users; --").fetchall()
[(u'; drop table users; --',)]
何止钟意 2024-12-05 21:12:21

如果你正确使用的话,psycopg2(通过 DB-API)会自动引用以防止 SQL 注入。 (python 方式是错误的;您必须将参数作为参数传递给查询命令本身。)

错误:

cur.execute('select * from table where last="%s" and first="%s"'
     % (last, first))

正确:

cur.execute('select * from table where last=%s and first=%s',
     (last, first))

注意:您不使用 %,并且你不会在你的价值观周围加上引号。

MySQLdb 和 sqlite3 的语法略有不同。 (例如,sqlite 使用 ? 而不是 %s。)

此外,对于 psycopg2,即使您正在处理数字或其他类型,也始终使用 %s。

psycopg2 (via DB-API) will automatically quote to prevent SQL injection, IF you use it properly. (The python way is wrong; you have to pass the parameters as arguments to the query command itself.)

WRONG:

cur.execute('select * from table where last="%s" and first="%s"'
     % (last, first))

RIGHT:

cur.execute('select * from table where last=%s and first=%s',
     (last, first))

Note: you don't use %, and you don't put quotes around your values.

The syntax is slightly different for MySQLdb and sqlite3. (For example, sqlite uses ? instead of %s.)

Also, for psycopg2, always use %s even if you're dealing with numbers or some other type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文