简体   繁体   中英

Python psycopg2 string interpolation format vs %

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

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.

Yes, it does. String interpolation methods are fragile because they allow SQL injection attack. Using external (user-provided) data as a parameters in parametrised queries (instead of building query string) makes this kind of attack impossible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM