Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Prepared Statements. Problems with SELECT IN

I'm having an issue with a prepared statement in Python I can't solve so far.

The Query, which should be execute is e.g.:

 SELECT md5 FROM software WHERE software_id IN (1, 2, 4)

So I tried to execute a Query like this:

software_id_string = "(2, 3, 4)"
cursor.execute("SELECT md5 FROM software WHERE software_id IN %s", 
                software_id_string)

The Problem is that there are '' added to the string --> '(2, 3, 4)', so that the Query will be:

SELECT md5 FROM software WHERE software_id IN ''(2, 3, 4)''

I've also tried to rebuild the Script like this:

software_id_string = " 1 OR software_id = 2"
cursor.execute("SELECT md5 FROm software WHERE software_id = %s", 
              software_id_string)

This works only for the first id, which will be submitted (in this case 1), because the OR-part won't be interpeted as an SQL Statement...

Is there any possibility to fix the issues with the prepared statements?

like image 954
pmuens Avatar asked Feb 24 '23 00:02

pmuens


1 Answers

You need one placeholder for each item in your parameter list.
You can use string operations to get that part done:

  1. Create one %s for each parameter, and
  2. Join those together with a comma.

In the next step you can pass your two arguments to execute() as recommended in the DB-API documentation.

software_id_string = (1,2,4)
qry = '''SELECT md5 
           FROM software 
          WHERE software_id IN (%s)''' % ','.join(['%s']*len(software_id_string))
# // 'SELECT md5 FROM software WHERE software_id IN (%s,%s,%s)'
cursor.execute(qry, software_id_string)
like image 112
mechanical_meat Avatar answered Feb 26 '23 21:02

mechanical_meat