Skip to content
Advertisement

How to avoid SQL injection on query

My SQL query construction in python code is:

query = '''
SELECT {return_col} 
FROM {table_name}   
'''.format(colA, tableA)

When I run Bandit security tool, it says “Possible SQL injection vector through string-based query construction.”

How do I avoid it?

Advertisement

Answer

Best practices recommend to avoid to dynamically build the query and instead use a parameterized query. But the goal is precisely to avoid what you are doing here: prevent a forged parameter to allow an arbitrary query.

If you know why you allow to query any field on any table, and if the account running the query has only SELECT privilege on the database, then you can ignore the warning: it just says that you could allow requests on any table… what you want to do!

But kindly examine the security implications. In some use cases it may be perfectly fine, in others it could be terrible.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement