2

I need to query to a database and filter on a where link in (....). The issue is the (...) since that "tuple" is dynamic. If I do it like this:

input_links = get_links() # [<link1>,...]
query = f"SELECT * from myTable where link in {tuple(input_links)}

that works fine unless input_links contains one link then the last part becomes (link1,) thus breaking the query.

I've tried using

input_links = get_links() # [<link1>,...]
link_tpl = f'({",".join(input_links)})'
query = f"SELECT * from myTable where link in {link_tpl}

but that encloses the entire argument in the tuple in one quote e.g ('link1,link2,link3') instead of ('link1','link2','link3').

I know I can just do an

if len(input_links)==1:
   query = f"SELECT * from myTable where link={input_links[0]}"
else:
   f"SELECT * from myTable where link in {tuple(input_links)}

but it just bothers me that I cannot have it as one statement.

CutePoison
  • 4,679
  • 5
  • 28
  • 63

3 Answers3

3

You can map each item in input_links to a string formatter:

query = f'''SELECT * from myTable where link=({', '.join(map("'{}'".format, input_links))})'''
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

Had this headache a few weeks back. Ended up doing something like this:

'(%s)' % ', '.join(map(repr, input_links))

Output:

   ...: input_links = [link1]
   ...: print('(%s)' % ', '.join(map(repr, input_links)))
   ...:
   ...: input_links = [link1, link2]
   ...: print('(%s)' % ', '.join(map(repr, input_links)))
(link1)
(link1, link2)

Based from this answer.

Brian Destura
  • 11,487
  • 3
  • 18
  • 34
0

Check this out. Assuming the links as '1','2'...:

l=['1','2']
def check_tup(l):
    k=','.join(f"'{i}'" for i in l)
    return f'({k})'
print(f"SELECT * from myTable where link in {check_tup(l)}")

Outputs:

SELECT * from myTable where link in ('1','2')

If l=['1']:

SELECT * from myTable where link in ('1')