According to the psycopg2 documentation (http://initd.org/psycopg/docs/connection.html) it states:
Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.
In the warning it specifically references not doing something like this:
cur.execute(SQL % data)
Does this warning also apply to the following using format?
cur.execute(SQL.format(data))
I do not know the internals of format, but I am assuming it is using % string interop underneath which would make it's usage unadvisable
答案 0 :(得分:0)
SQL.format()
(where SQL
is a regular ol' Python string) doesn't actually use %
interpolation under the hood, but it has the same pitfall: the values you substitute in are not properly escaped for SQL (how could they be; Python has no idea that SQL
is a SQL statement) and your SQL statement could then be subject to injection attacks.
Your various SQL modules have methods to prevent this issue and you should use them instead.
答案 1 :(得分:0)
是的,确实如此。字符串插值方法很脆弱,因为它们允许SQL注入攻击。使用外部(用户提供的)数据作为参数化查询中的参数(而不是构建查询字符串)使得这种攻击变得不可能。