Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to safely generate a SQL LIKE statement using python db-api

I am trying to assemble the following SQL statement using python's db-api:

SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%';

where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried

beginningOfString = 'abc'

cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%', beginningOfString) 
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%%', beginningOfString)

I am out of ideas; what is the correct way to do this?

like image 740
laramichaels Avatar asked Jan 19 '10 22:01

laramichaels


2 Answers

It's best to separate the parameters from the sql if you can. Then you can let the db module take care of proper quoting of the parameters.

sql='SELECT x FROM myTable WHERE x LIKE %s'
args=[beginningOfString+'%']
cursor.execute(sql,args)
like image 76
unutbu Avatar answered Nov 20 '22 13:11

unutbu


EDIT:

As Brian and Thomas noted, the far better way to do this would be to use:

beginningOfString += '%'
cursor.execute("SELECT x FROM myTable WHERE x LIKE ?", (beginningOfString,) )

since the first method leaves you open to SQL injection attacks.


Left in for history:

Try:

cursor.execute("SELECT x FROM myTable WHERE x LIKE '%s%%'" % beginningOfString)
like image 21
Sean Vieira Avatar answered Nov 20 '22 12:11

Sean Vieira