0

I am using the python sqlite3 package to execute queries. To avoid the sql injection issues I am using placeholders for the input parameters. In my case the order by column is also coming from an input parameter.

So I wrote my code as below:

column = 'somecolumn'
query= "select name from MyTable where id = ? Order by ?"
params = (id , column)
cur = conn.cursor()
cur.execute(query,params)

The placeholder substitution did not work for sql keyword Order by. Is there any way that I can make this work without having to worry about sql injections?

Thanks, Gaurav

  • Why not hardcode the column? Surely that's not vulnerable to SQL injection. (Also, you can only use placeholders for values, not column or table names). – Irfan434 Oct 31 '17 at 05:50
  • Also, if you are getting the column name from the user, you should use *if statements* to make sure you are getting a valid column, and hardcode the column name inside each if statement. – Irfan434 Oct 31 '17 at 05:51
  • @Ahmad Thanks for the reply. Yes, i know table/column names/keywords can't have a placeholder. Hard coding is not an option. Also this is a generic code and the input parameter can be any column name for any table and so checking for valid column name is also not possible. – Gaurav Bhattacharjee Oct 31 '17 at 06:02
  • This question is not exactly duplicate. The perspective of the question is different. https://stackoverflow.com/questions/39559072/sqlite3-query-order-by-parameter-with-notation does provide an answer as what to use to overcome the issue. I can use %s also for replacement. But my query is whether there would be any issues w.r.t. sql injection. – Gaurav Bhattacharjee Oct 31 '17 at 07:00

0 Answers0