Python MySQLdb string expansion without adding quotes

I would like to use string substitution for a comma separated list, for example:

query = """SELECT id, name, image_id
           FROM users
           WHERE id IN (%s)
           """
values = (','.join(uids))
results = dbc.getAll(query, values

Fulfills the request:

SELECT id, name, image_id
FROM users
WHERE id IN ('1,2,3')

Which does not work properly.

How can I do this to get a request without quotes, for example:

SELECT id, name, image_id
FROM users
WHERE id IN (1,2,3)
+3
source share
2 answers

Let MySQLdb do the entire replacement of the argument. In this case, the expected argument valuesshould be a sequence (1,2,3), not a string '1,2,3':

query = """SELECT id, name, image_id
           FROM users
           WHERE id IN %s
           """    
values = uids
results = dbc.getAll(query, [values])
+3
source

For me, it worked like this:

cursor.execute(sql, (pids_list,))

and I made sure that the pids_list elements are integers , not strings.

+1
source

Source: https://habr.com/ru/post/1769614/


All Articles