问题描述
我正在使用SQLAlchemy连接到Python中的不同数据库,但是没有使用ORM支持,因为由于多种原因而无法实现。
I am using SQLAlchemy to connect to different databases in Python, but not with the ORM support as this cannot be implemented due to several reasons.
主要是我建立了一个复杂的SQL查询,使用类似
Mainly I do build a complex SQL query using things like
sql += "AND fieldname = '%s'" % myvar
对于我来说,这不是SQL注入的问题,因为数据始终来自受信任的来源,即使该来源是受信任的它可能包含可能破坏查询的字符,例如'
,%
或 _
。
In my case is not a problem of SQL injection as the data is always from a trusted source but even if the source is trusted it could contain characters that could break the query like '
, %
or _
.
主要是我需要对它们进行转义,并且我想知道是否存在可以重新使用的转义功能。
Mainly, I need to escape them, and I wonder if there is an already existing escape function that I could re-use.
推荐答案
您不应尝试实现自己的转义,而应使用SQLAlchemy的内置方法:
You should not try to implement your own escaping, but should instead use SQLAlchemy's builtin method:
sql = 'select * from foo where fieldname = :name'
result = connection.execute(sql, name = myvar)
这篇关于在SQLAlchemy中手动构建SQL查询时如何正确转义字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!