0

I am using sqlite3 which requires us to put trailing comma after the last item of tuple (of values). The example below should return an expected output of (2, 3,). Is there a builtin function that can handle this?

args = 2, 3

print(args)
# (2, 3)

print((args,))
# ((2, 3),)

sqlite3 without trailing comma after 'John'

import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE first_name = ?", ('John'))
print(c.fetchall())
conn.close()

# sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
# current statement uses 1, and there are 4 supplied.

sqlite3 with trailing comma after 'John'

import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE first_name = ?", ('John',))
print(c.fetchall())
conn.close()

# [(1, 'John')]
16
  • 3
    Where does sqlite3 require that?
    – melpomene
    Aug 31, 2019 at 2:13
  • I've got sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. The way I solve the problem is to add a trailing comma on the last part of the tuple.
    – user10732646
    Aug 31, 2019 at 2:17
  • 1
    If you have a problem with your code, you need to show your code.
    – melpomene
    Aug 31, 2019 at 2:19
  • 3
    Trailing commas are only required for tuples of 1 element Aug 31, 2019 at 2:19
  • 1
    @joumaico, sqlite doesn't require the trailing comma. (2,3) and (2,3,) are completely identical; no code, sqlite included, can tell them apart. Aug 31, 2019 at 2:22

2 Answers 2

2

Your statements differ in the following detail:

('John')  ## this is not a tuple, it just evaluates to the string 'John'
('John',) ## this *is* a tuple, containing a string 'John' as its only element

However, that difference exists only in the case where a tuple has only one item.

('John', 'Sue') == ('John', 'Sue',)

...is a true statement, because as soon as you have more than one item, the value unambiguously parses as a tuple; no trailing comma is needed.

2
  • Thank you, accidentally I args = 1, to make the args a tuple instead of string.
    – user10732646
    Aug 31, 2019 at 2:35
  • I have finally seen the exact term for this: In Python, a tuple containing a single value must include a comma. For example, ('abc') is evaluated as a scalar while ('abc',) is evaluated as a tuple. Thank you Charles. dev.mysql.com/doc/connector-python/en/…
    – user10732646
    Aug 31, 2019 at 10:00
0

This is not possible. Because you are using a tuple and a comma is required if you have one element. Use a list instead by replacing your parenthesis () with brackets [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.