开发者

Python MySQLdb string substitution without added quotations

开发者 https://www.devze.com 2023-01-20 04:50 出处:网络
I\'d like to use string substitution for a comma-separated list, such as: query = \"\"\"SELECT id, name, image_id

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 ex开发者_开发问答ecutes 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)


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])


For me it worked this way:

cursor.execute(sql, (pids_list,))

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

0

精彩评论

暂无评论...
验证码 换一张
取 消