0

I am trying to return something like 'GBP' in Python after running a fetch query from a SQLite database, but I am getting ('GBP',) instead. I know this question has been asked before but I am very new to Python and didn't understand any of the answers I read. Could someone please help?

a = input("Enter ID of customer: ")
currency1 = """SELECT Currency FROM Customers WHERE ID='{}'""".format(a)   
cur.execute(currency1)
result1 = cur.fetchone()   
a3 = tuple(result1)
print(a3)

It has to be a tuple or a string because it has to be hashable. I know there's likely an easy fix but I can't seem to get it. The comma in the return is stopping me from moving on to the next stage. Thanks!

stevethfc
  • 13
  • 1
  • You should not be formatting the SQL manually. `execute` takes `parameters` argument which does that. See https://www.python.org/dev/peps/pep-0249/#id15 – zvone Dec 17 '20 at 00:50

1 Answers1

1

A python tuple will always have a comma. As input it's required because without it it's ambiguous as a tuple or an expression. I expect as output, it's a similar reason. So if you need a tuple, then you have to have the comma.

However, if you just need the 'GBP' (which is hashable), then you can get the first element of the tuple. The query will always return a list/tuple because you can have multiple parts of the SELECT statement. But if you only have/need the one, then just dereference it.

a = input("Enter ID of customer: ")
currency1 = """SELECT Currency FROM Customers WHERE ID='{}'""".format(a)   
cur.execute(currency1)
result1 = cur.fetchone()[0]
print(result1)
saquintes
  • 1,074
  • 3
  • 11