2

I have the following code and it works, but I need to understand why there is a comma after the variable id_to_remove, can someone explain to me why that has to be there? (I bolded the part I don't understand)

def delete_user(id_to_remove):
    sql = "DELETE FROM USERS WHERE ID = ?"
    conn = create_connection()
    cursor = conn.cursor()
    **cursor.execute(sql, (id_to_remove, ))**
    conn.commit()
    conn.close()

So I don't know why its id_to_remove, and not just cursor.execute(sql,(id_to_remove))

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ryan
  • 23
  • 3
  • `(id_to_remove, )` is a tuple containing one item, `id_to_remove`. – Thierry Lathuille Dec 31 '19 at 19:34
  • 1
    That is because execute expects as second parameter an iterable (a list) and if you do not put the comma there (id_to_remove) just between parentheses will transformed into an int. – Marco Dec 31 '19 at 19:34
  • Check [One Element Tuples](https://wiki.python.org/moin/TupleSyntax), and/or [This](https://stackoverflow.com/questions/12876177/how-to-create-a-tuple-with-only-one-element) – Grijesh Chauhan Dec 31 '19 at 19:36
  • Thank you so much, got some reading to do. :0) – Ryan Dec 31 '19 at 19:38

1 Answers1

2

Because it will replace all the ? values with the ones in the tuple. If you don't put a comma then it is a single value, you need to add it to construct a single value tuple.

marcos
  • 4,473
  • 1
  • 10
  • 24