0

I know that the params parameter is the more sanitized solution to avoid SQL injections in pandas.read_sql, but I am still not sure if it is safe to let a random user input raw data inside a SQL in the function.

For example, let the below function avaiable for an unknown user who can pass a list with the clients_ids:

def sql_client(connection, clients_ids):
    
    df = pd.read_sql(f"select * from clients where clients_ids in {tuple(clients_ids)}",
                     connection)

    return df

Is this function safe from SQL injections?

kovashikawa
  • 1,121
  • 9
  • 15
  • 1
    My gut answer would be 'no.' Python does escape quotes in strings, but there are a lot of complicated rules about how to correctly escape untrusted SQL strings, and I would not bet that Python does it in exactly the way your SQL server wants. I can't think of a counterexample, though. – Nick ODell Feb 09 '22 at 22:21
  • 1
    The tuple is being inserted by the f-string formatting, not `read_sql`. So it's too late for Pandas to sanitize it. You should use parameters. See https://stackoverflow.com/questions/24408557/pandas-read-sql-with-parameters – Barmar Feb 09 '22 at 22:47

0 Answers0