简体   繁体   中英

How to use python to elegantly parameterize a SQL DELETE statement?

I have a list of user_ids to be deleted: The user_ids are str type.

users = ['user1', 'user2', 'user3']

Currently I'm deleting them with these codes

query_delete = 'delete from users where user_id in ({});'.format('?, '*len(users))
# delete from users where user_id in (?, ?, ?, );

query_delete.replace(", )", ")")
# delete from users where user_id in (?, ?, ?);

cursor.execute(query_delete, users)

I think use the .format('?, '*len(users)) to paramize the query is not elegant enough.
Is there a better way to make the code more elegantly and readable?

EDIT
I'm using python 3.6.5 on CentOS 7, and MySQL 8. I want the query executed as

delete from users where user_id in ('user1', 'user2', 'user3');

Depending on what database and database interface library you are using, it might be easier to use the parameter-passing mechanism of the library. For example, with PostgreSQL and psycopg2, something like this should work:

users = [ 'user1', 'user2', 'user3' ]
cursor.execute("DELETE FROM user WHERE user_id = ANY (%(u)s)",
               { 'u': users })

(typed without testing, so probably full of trivial mistakes).

This would also eliminate the risk of SQL injections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM