Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySQLdb string substitution without added quotations

Tags:

python

mysql

I'd like to use string substitution for a comma-separated list, such as:

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

This executes the query:

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

Which does not work as expected.

How can I do a substution so that I get the query without the quotations, such as:

SELECT id, name, image_id
FROM users
WHERE id IN (1,2,3)
like image 594
ensnare Avatar asked Jun 13 '26 22:06

ensnare


1 Answers

Let MySQLdb do the entire argument substitution. In this case, the expected argument, values, should be the sequence (1,2,3), rather than the string '1,2,3':

query = """SELECT id, name, image_id
           FROM users
           WHERE id IN %s
           """    
values = uids
results = dbc.getAll(query, [values])
like image 148
unutbu Avatar answered Jun 16 '26 11:06

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!