I am developing this program and for some reason, I keep getting this error. Is this an Ubuntu caused error, or something in my code that it crashing my program?
I am accessing a database and trying to remove the following characters from output: and, via value.translate(dictionary_of_bad_characters)
. That's where I get my error.
def get_data(plu): # Get the data needed
global value # Set the variable value to global
conn = sqlite3.connect('plus.sqlite') # Connect to the sqlite3 database
cursor = conn.cursor() # Set cursor as the cursor for plus.sqlite
results = cursor.execute('SELECT value FROM plus WHERE plu=?', [plu])
# Above code gets the data value for value with the PLU of plu
value = results.fetchone() # Get the results of value
data = [row[0] for row in results.fetchall()]
translation_table = dict.fromkeys(map(ord, '+-(),'), None)
# Above code creates a table with the mapped characters
value = value.translate(translation_table)
# Above code removes any unnescessary characters from value
response = { 'PLU': plu,
'Value': value
} # Create the response variable
value = int(value) # Convert value to type integer
cursor.close() # Close the cursor
conn.close() # Close the connection
return(value) # Return to the program flow
This error indicates that
value
is a tuple, and not a string as you might expect. This indicates a problem with your application.Here the problem is that
fetchone()
returns a one-tuple. You should change from this line:to this (notice the comma after
value
):or this (not recommended):
But why is
fetchone()
returning a tuple instead of a string? Because you canSELECT
multiple columns. Consider for example the following SQL statement:In this case,
fetchone()
will return a three-tuple.Writing
value, = fetchone()
you are telling Python that you are expecting a one-tuple and you want that single item placed intovalue
. If you were expecting the three-tuple, you'd have usedcolumn_a, column_b, column_c = resulsts.fetchone()
.This is the reason why you should prefer
value,
overfetchone()[0]
.Bonus tip: I noticed you are using Python 3. In this case, you can write:
Speeding up your code and making it more clean.