Reputation: 101
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 sql
statement. Is this possible in Python?
Upvotes: 0
Views: 770
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