2

我有一个prodemployees看起来像这样的列表:

['prd1 employe4 employe2', ' prd2 employe2']

我需要这个列表的值来动态创建查询的“where”语句,我需要输出是这样的:

WHERE (product = 'prd1' AND employe IN ('employe4','employe2'))
OR
(product = 'prd2' AND employe IN ('employe2'))

我尝试在空白处拆分列表的每个值,并创建一个包含结果值的子列表,但未能使用这些值。

我是 Python 新手,不胜感激。

splitOnSpace = []
for i in range(len(prodemployees)) :
  splitOnSpace = prodemployees[i].split()
    for j in range(len(splitOnSpace)) : 
       #this is where I should do something with splitOnSpace[j] I guess...
4

1 回答 1

7

拆分后您有一个列表,您可以对该列表进行切片以获取子列表:

for prod_emp in prodemployees:
    prod_emp = prod_emp.split()
    prod, emp = prod_emp[0], prod_emp[1:]

这里prod设置为拆分字符串的第一个元素,emp除了第一个元素之外的所有元素的列表:

>>> prodemployees = ['prd1 employe4 employe2', ' prd2 employe2']
>>> for prod_emp in prodemployees:
...     prod_emp = prod_emp.split()
...     prod, emp = prod_emp[0], prod_emp[1:]
...     print prod, emp
... 
prd1 ['employe4', 'employe2']
prd2 ['employe2']

从现在开始,我将使用 SQL 参数来执行实际查询。构建过滤器,然后将所有拆分参数链作为一个长参数列表传递:

from itertools import chain

filters = filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
cursor.execute('SELECT * FROM sometable WHERE {}'.format(
                   ' OR '.join(filters)),
               chain.from_iterable(pe.split() for pe in prodemployees))

这里filters使用参数占位符生成合适的 SQL:

>>> filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
>>> list(filters)
['(product=%s AND employee in (%s, %s))', '(product=%s AND employee in (%s))']
>>> filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
>>> 'SELECT * FROM sometable WHERE {}'.format(
...                    ' OR '.join(filters))
'SELECT * FROM sometable WHERE (product=%s AND employee in (%s, %s)) OR (product=%s AND employee in (%s))'

.execute()将从chain.from_iterable()提供​​的参数中填写您的查询:

>>> list(chain.from_iterable(pe.split() for pe in prodemployees))
['prd1', 'employe4', 'employe2', 'prd2', 'employe2']

此处使用的%s占位符特定于某些类型的数据库适配器;其他人可以?改用;检查您的数据库适配器文档。

于 2013-06-18T14:44:16.287 回答