将信息输入数据库时​​出现TypeError

时间:2016-07-12 05:08:51

标签: python sqlite

我编写了以下代码来将信息输入数据库。

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

我试图编写一个程序,如果他们的新分数高于他们当前存储的高分,则会更新并存储用户高分。如果用户不存在,那么它将创建一个具有分数的新用户。

但是,根据上述代码,我在第12行获得TypeError: object of type 'NoneType' has no len()

我面临的这个问题是什么?有什么建议吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

来自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.

所以当没有这样的用户时,你会得到None,而不是空列表。

您的if可能应该是:

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

此外,您的第二个查询UPDATE scores SET score=?将更新每个人的分数;不只是这个用户。您需要UPDATE scores SET score=? WHERE username=?,然后传递user