简体   繁体   中英

Python - Building a dynamic sql query with `-` as a range

I've done some searching and thought I'd ask before trying to reinvent the wheel.

I'm looking to build a sql query with an unknown number of parameters. The parameters are of type int, they are item numbers.

The user can input as many items as they like, in the form 1, 2, 3-10, 12

I need to build a sql style query (actually for arcpy) that will return all these values for field item.

I can easily pull these all into a list such as mylist = [1,2,3,4,5,6,7,8,9,10,11,12]

But then I need to build the query, I'm guess it would be something like

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

Thanks very much

Jon

Simply you can do it this way,

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))

Check what result is,

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

Query it,

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

if sql style query is fully supported, you could put it in a list, and generate the query like this:

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

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