Categories
Python Answers

How to imploding a list for use in a Python MySQLDB IN clause?

Spread the love

Sometimes, we want to imploding a list for use in a Python MySQLDB IN clause

In this article, we’ll look at how to imploding a list for use in a Python MySQLDB IN clause.

How to imploding a list for use in a Python MySQLDB IN clause?

To imploding a list for use in a Python MySQLDB IN clause, we call cursor execute with a tuple.

For instance, we write

format_strings = ",".join(["%s"] * len(list_of_ids))
cursor.execute(
    "DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings, tuple(list_of_ids)
)

to call cursor.execute with SQL string that has the the format_strings interpolated into it.

And then we use tuple(list_of_ids) to inmplode a list of items in the tuple into the placeholder in the format_strings list.

Conclusion

To imploding a list for use in a Python MySQLDB IN clause, we call cursor execute with a tuple.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *