2012-03-20 33 views
1

我与蟒蛇plugins.I工作使用列表如下存储一些值:Python的列表中查询

known_stn.append('1') 
known_stn.append('2') 

我的查询是

query=("SELECT survey, station FROM stat WHERE stat.station IN (%s) AND station.survey = '2011410'" %known_stn) 

发生了WHERE station.station IN (['1', '2'])错误,如清单包含[]括号。 我试图更换那些括号,但他们并没有取代。

是否有任何其他数据结构使用?或者出路来代替方括号...

+1

“Python插件”并不意味着任何afaik。你用什么来与SQL接口? – katrielalex 2012-03-20 13:04:03

+0

我使用postgresSQL作为GUI的database.and pyqt4设计器..... – poonam 2012-03-20 13:05:57

+1

请勿自己格式化您的查询字符串;这是要求SQL注入攻击。在你用来执行查询的任何内容中使用内置的格式。 (下面的答案是正确的,因为您需要首先将该列表加入字符串中) – katrielalex 2012-03-20 13:10:41

回答

2

您需要格式化您的列表,你用它替换到模板之前字符串串:

"where (%s) blah" % ', '.join(map(str,known_stn)) 

http://docs.python.org/library/stdtypes.html#str.join

map(str,known_stn)转换元件thems小精灵在加入之前加入一串。

另外,请注意有关SQL注入的警告。

4

您需要将列表转换到一个字符串:

>>> my_list = [1,2,3] 
>>> str(my_list) 
'[1, 2, 3]' 
>>> map(str, my_list) 
['1', '2', '3'] 
>>> ','.join(map(str, my_list)) 
'1,2,3' 
>>> 'select ... where foo in (%s)' % ','.join(map(str, my_list)) 
'select ... where foo in (1,2,3)'