I have a list of values that I'd like to use in an IN
clause for an SQL (SQL Server) statement to be executed with pyodbc. Example:
files = ['file1', 'file2', ...] # this list can have a variable number of elements
con = pyodbc.connect(...)
# What I'd like to do
result = con.cursor().execute('SELECT * FROM sometable WHERE file_name IN (?)', files)
However when I execute the statement above I get an error such as this:
ProgrammingError: ('The SQL contains 1 parameter markers, but 18 parameters were supplied', 'HY000')
I can generate a variable parameter string using something like:
params = ','.join(['?']*len(files))
query = 'SELECT * FROM sometable WHERE file_name IN ({})'.format(params)
result = con.cursor().execute(query, files)
But doing so would put me at risk for SQL injection, if I understand correctly. Is there a way to accomplish this safely?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…