2016-07-12 15 views
0

Ich habe den folgenden Code geschrieben, um Informationen in eine Datenbank einzugeben.TypeError beim Eingeben von Informationen in die Datenbank

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 

Ich versuche, ein Programm zu schreiben, die hohe Werte aktualisiert und speichern Benutzer, wenn ihre neue Punktzahl größer ist als ihr aktueller High-Score ist, die gespeichert wird. Wenn der Benutzer nicht existiert, erstellt er einen neuen Benutzer mit seiner Punktzahl.

jedoch mit dem obigen Code, ich bin immer TypeError: object of type 'NoneType' has no len() in Zeile 12.

Was dieses Problem ist, dass ich mit Blick auf bin? Irgendwelche Vorschläge ?

Vielen Dank im Voraus!

Antwort

1

Von 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. 

Also, wenn es keinen solchen Benutzer, werden Sie None zurück, nicht eine leere Liste erhalten.

Ihre if sollte wohl dann sein:

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

Zusätzlich Ihre zweite Abfrage UPDATE scores SET score=? wird die Punktzahl für jeden aktualisieren; nicht nur dieser Benutzer. Sie benötigen UPDATE scores SET score=? WHERE username=? und geben dann die user ein.