2013-04-09 69 views
1

我已經完成了一些搜索,並且在嘗試重新發明輪子之前先要問。Python - 使用`-`作爲範圍構建動態sql查詢

我正在尋找建立一個SQL查詢與未知數量的參數。參數是int類型的,它們是項目編號。

用戶可以輸入儘可能多的項目,因爲他們喜歡,形式1,2,3-10,12

我需要建立一個SQL樣式的查詢(實際上是ArcPy中),將返回所有這些值爲實地項目。

我很容易就能把這些所有成列表,諸如 MYLIST = [1,2,3,4,5,6,7,8,9,10,11,12]

但我需要建立查詢,我想這會是這樣的

item = 1 or item = 2 or ...... 

非常感謝

喬恩

+1

你的意思是「選擇* from your_table where id in(1,2,3,4,5,6)「?? – pinkdawn 2013-04-09 01:41:18

回答

0

如果SQL查詢的風格完全支持,你可以把它放在一個列表,並生成查詢像這樣:

items = [1,2,3,4,5] 
query = 'select * from table where item in (%s)' % ','.join(items) 
1

只要你能做到這樣,

user_input = '1, 2, 3-10, 12' 
data = [item for item in user_input.split(', ')] 
result = [] 

for d in data: 
    if '-' in d: 
     result.extend(range(int(d.partition('-')[0], int(d.partition('-')[2])+2)) 
    else: 
     result.append(int(d)) 

檢查是什麼結果,

>>> result 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12] 

查詢它,

'SELECT * FROM table WHERE id in (%s)' % ','.join(str(item) for item in result) 
+0

非常感謝! – jpedder 2013-04-09 02:22:33

+2

@jpedder確保你不使用這個不受信任的輸入。使用字符串插值生成SQL查詢可讓您廣泛開放SQL注入。 – 2013-04-09 02:35:01