stats con chris
stats con chris

Reputation: 337

How to use MySQL SELECT WHERE IN (single tuple,) Python... when tuple length=1 it shows an error

I have 2 tuples a and b

print(a)
(1,2,3,4,5)

print(b)
(1,)

As you can see the second one has a single value... For the first one I use

query_a = 'SELECT something FROM mytable WHERE id IN {};'.format(a)

It works perfectly.

If I do the same for b, it doesn't work. It shows:

Error: blah blah blah ..WHERE id IN (1,);': (1064, "You have an error in your SQL syntax...

I believe the error is because of the tuple comma -> (1,) How do I solve this. I tried

query_b = 'SELECT something FROM mytable WHERE id IN ();'.format(b)

but it also doesn't work. How do I fix this in one line? Thanks.

Upvotes: 1

Views: 1559

Answers (2)

stats con chris
stats con chris

Reputation: 337

Thanks. It works. To make it more clear the answer is:

query_a = 'SELECT something FROM mytable WHERE id IN {};'.format(str(a)[:-2] + str(a)[-1])

Upvotes: 0

Devansh Sharma
Devansh Sharma

Reputation: 331

You can do some simple string manipulations to remove the comma.

'Tuple without comma: {}'.format(str(b)[:-2] + str(b)[-1])

This should work regardless of the tuple length.

Also as a side note, the {} is part of syntax for Format Strings in Python. You cannot replace that with () to make it to work.

Upvotes: 2

Related Questions