Python - Building a dynamic sql query with `-` as a range -
i've done searching , thought i'd ask before trying reinvent wheel.
i'm looking build sql query unknown number of parameters. parameters of type int, item numbers.
the user can input many items like, in form 1, 2, 3-10, 12
i need build sql style query (actually arcpy) return these values field item.
i can pull these list such mylist = [1,2,3,4,5,6,7,8,9,10,11,12]
but need build query, i'm guess like
item = 1 or item = 2 or ......
thanks much
jon
simply can way,
user_input = '1, 2, 3-10, 12' data = [item item in user_input.split(', ')] result = [] d in data: if '-' in d: result.extend(range(int(d.partition('-')[0], int(d.partition('-')[2])+2)) else: result.append(int(d))
check result is,
>>> result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
query it,
'select * table id in (%s)' % ','.join(str(item) item in result)
Comments
Post a Comment