简体   繁体   中英

Unspecified number of variables in an sql script in python

I want to run a query to an sql database through python similar to this:

cursor.execute('SELECT * FROM mf WHERE col2 = ? or ?', (country))

However, I want to include an unspecified number of or options in this section of the code, and the user specifies the countries in a separate parameter file, ie I don't know how many ? to put in the code because it's variable. Is it possible to do this in the SQL code?

First off, your SQL code is not valid. You want either col2 = ? or col2 = ? col2 = ? or col2 = ? or (better) col2 IN (?, ?, ?) .

It is not possible to use parameterized queries like this with an unknown number of parameters. On the other hand, you must use parameterized queries for safety. The solution is to construct a parameterized query using the IN form based on knowing the number of parameters in the parameter list:

params = get_params_from_file_or_somewhere_else() # wherever you have the params.

qmarks = ', '.join('?' for param in params) # string with the "right" number of "?"

sql = 'SELECT * FROM mf WHERE col2 IN ({});'.format(qmarks)

cursor.execute(sql, params)

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