-1

I need to convert a list to tuple I am passing this tuple to a sql in clause. When there is only one element in the list the tupple is retrieving and extra element how do we avoid that. I referred the list to tuple below but unable to find the answer to avoid extra element

Convert list to tuple in Python

>>> taskid="10030"
>>> l = taskid.split(",")
>>> l
['10030']
>>> t = tuple(l)
>>> t
('10030',)
 >>> query = f"""select * from table1 where task_id in  {tuple(t)} ) query_temp"""

Please let know the apt solution

Rafa
  • 487
  • 7
  • 22
  • What do you mean it's receiving an extra element? You're splitting a string and the delimiter exists, so you get a list with two elements. The tuple isn't going to magically do away with an actual result. – Silvio Mayolo Jul 07 '21 at 02:47
  • 1
    Do not use interpolation to construct your query. Create a parameterized query using whatever method your SQL library supplies, something like `cursor.execute("select * from table1 where task_id in %s", (t,))`. – chepner Jul 07 '21 at 02:50

2 Answers2

0

Just like @chepner said do not use interpolation to construct your query. For example with sqlite3 you can pass the any variables as parameters so that each ? will be replaced with the according parameter from the tuple:

cursor.execute("select * from table1 where task_id in ?", t)

Also the "," in ('10030',) does not indicate that there is a second item in the tuple rather that it is a tuple:

thistuple = ("apple",)
print(type(thistuple)) #class tuple

#NOT a tuple
thistuple = ("apple") #class str
print(type(thistuple))

src: https://www.w3schools.com/python/trypython.asp?filename=demo_tuple_one_item

sputnick567
  • 324
  • 5
  • 12
0

If all you want is a query with parameter then don't use tuple, a single element tuple will have a comma.

Based on your approach you can do it like this (using join):

l = ['10030']
query_param = ",".join(l)
query = f'select * from table1 where task_id in ({query_param})  query_temp'
print(query)

Output:

select * from table1 where task_id in (10030) query_temp

If list contain more than 1 element then:

l = ['10030','111','22']
query_param = ",".join(l)
query = f'select * from table1 where task_id in ({query_param})  query_temp'
print(query)

Output:

select * from table1 where task_id in (10030,111,22) query_temp

Abhi
  • 995
  • 1
  • 8
  • 12