kfk
kfk

Reputation: 841

Parameterized sql queries and safety

I am creating a web service that is supposed to give a lot of flexibility on exploring datasets. Now, in order to do this in SQL, I am finding it easier to create manually the query instead than using parameters (as below with 'select'). This would the make generation of where sql queries much easier (see tuples of where variable below) and according to, for example, this: http://docs.python.org/library/sqlite3.html; much less safe.

My question is, is there a way to make this a safe option? Put in other words, is there a safe way to execute "manually" built queries?

What I am thinking is that if I make sure that the query being run starts with "SELECT", then I should be protected from queries that would alter the data. Is this a good idea? Are there better ways? Or parameterized queries is the only way to stay safe from SQL injections?

select = ['a','b']
where = [('a','=',1),('b','=',2)]
def retrieve(self,table,select,where='',groupBy=''):
   select = ','.join(select)
   sql = 'SELECT '+select+' FROM '+table
   self.cur.execute(sql)
   return self.cur.fetchall()

Upvotes: 0

Views: 700

Answers (1)

gutes
gutes

Reputation: 152

No. That's not a good idea. OWASP top 10 (Injection is in the first place) is a good source of information and best practices.

As a side note, you would probably want to use SQL Alchemy, very powerful and widely used. It will give you (I guess) all the flexibility you're looking for.

Upvotes: 4

Related Questions