简体   繁体   English

python中sql脚本中未指定数量的变量

[英]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:我想通过类似于这样的python运行对sql数据库的查询:

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?是否可以在 SQL 代码中执行此操作?

First off, your SQL code is not valid.首先,您的 SQL 代码无效。 You want either col2 = ? or col2 = ?你想要col2 = ? or col2 = ? col2 = ? or col2 = ? or (better) col2 IN (?, ?, ?) .或(更好) 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:解决方法是在知道参数列表中的参数个数的基础上,使用IN形式构造一个参数化查询:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM