Planet_Man
Planet_Man

Reputation: 101

Create multiple strings inside a string using python

I am new to using python to write sql strings and was wondering if someone could help me. So currently I am writing a sql statement like this,

   sql_statement = """SELECT * from some_database WHERE FirstName IN (%(first_names)s)"""
   first_names = ['fn1', 'fn2', 'fn3']

And I want the string to end up like this SELECT * from some_database WHERE FirstName IN ('fn1', 'fn2', 'fn3'), where each element in the list becomes its own string in the sqlstatement. Is this possible in Python?

Upvotes: 0

Views: 770

Answers (1)

Chris
Chris

Reputation: 22953

You can use str.format to accomplish this:

>>> sql_statement = """SELECT * from some_database WHERE FirstName IN {}"""
>>> first_names = ['fn1', 'fn2', 'fn3']
>>> 
>>> sql_statement.format(repr(tuple(first_names)))
"SELECT * from some_database WHERE FirstName IN ('fn1', 'fn2', 'fn3')"
>>> 

Caveat: While this is fine as just a plain string, be very careful using this as a SQL statement due to SQL injection. A better idea would most likely be to cursor.execute instead or the equivalent in your SQL API library.

Upvotes: 1

Related Questions