6

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

1 Answers1

8

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:

value = results.fetchone()

to this (notice the comma after value):

value, = results.fetchone()

or this (not recommended):

value = results.fetchone()[0]

But why is fetchone() returning a tuple instead of a string? Because you can SELECT multiple columns. Consider for example the following SQL statement:

SELECT a, b, c FROM my_table;

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 into value. If you were expecting the three-tuple, you'd have used column_a, column_b, column_c = resulsts.fetchone().

This is the reason why you should prefer value, over fetchone()[0].


Bonus tip: I noticed you are using Python 3. In this case, you can write:

translation_table = dict.fromkeys(b'+-(),', None)

Speeding up your code and making it more clean.