sid
sid

Reputation: 19

TypeError while entering information into database

I have written the following piece of code to enter information into a database.

import sqlite3

with sqlite3.connect('highscores.db') as conn:
    #Python 3 users, change raw_input to input.
    user = raw_input('Name: ')
    score = int(raw_input('Score: '))

    result = conn.execute("SELECT * FROM scores WHERE username=?", (user,))
    row = result.fetchone()

    #If the user does not exist then insert them into the table.
    if len(row) == 0:
        conn.execute("INSERT INTO scores(username, score) VALUES(?, ?)", (user,score))
    else:
    #If the user already exists then update their score if their new score is
    #greater than their current high score.
        if row[1] < score:
            conn.execute("UPDATE scores SET score=?", (score,))
    else:
         print "Current high score for {} is {}".format(user, row[1])
    check_result = conn.execute("SELECT * FROM scores")
    for row in check_result.fetchall():
    print row

I'm trying to write a program that will update and store users high scores if their new score is greater than their current high score that is stored. If the user doesn't exist then it will create a new user with their score.

However, with the above code, I'm getting TypeError: object of type 'NoneType' has no len() at line 12.

What is this issue that i'm facing? Any suggestions ?

Thanks in advance!

Upvotes: 0

Views: 44

Answers (1)

user94559
user94559

Reputation: 60143

From https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.fetchone:

fetchone()
Fetches the next row of a query result set, returning a single sequence, or None when no more data is available.

So when there's no such user, you'll get None back, not an empty list.

Your if should probably then be:

#If the user does not exist then insert them into the table.
if row is None:
    ...

In addition, your second query UPDATE scores SET score=? will update the score for everyone; not just this user. You need UPDATE scores SET score=? WHERE username=? and then pass in the user.

Upvotes: 1

Related Questions