cursor.fetchone()即使值存在也返回None

cursor.fetchone()即使值存在也返回None

问题描述:

我试图弄清楚如何从UserID中获取单个值并将其打印在控制台中.即使我正在搜索的UserID的Currency值为一个值,我当前的代码也会不断返回"None".

I am trying to figure out how to fetch a single value from a UserID and print it in the console. My current piece of code keeps returning "None" even though there is a value for Currency for the UserID I am searching.

cursor.execute("SELECT Currency FROM ServerUsers WHERE USERID = %s" % (userid))
    if cursor.fetchone():
        a = cursor.fetchone()
        print(a)

调用 execute 时,将计算并获取结果,并使用 fetchone / fetchmany / fetchall 进行检索.

When you call execute, the results are computed and fetched, and you use fetchone/fetchmany/fetchall to retrieve them.

在您的情况下,查询返回一个行作为结果,因此在 if 中调用 cursor.fetchone 会被提取并随后被丢弃,因此再次调用 fetchone 会产生 None ,因为指针已经前进到结果集中的唯一行.

In your case, your query returns a single row as the result, so calling cursor.fetchone in the if causes the result to be fetched and subsequently thrown away, so another call to fetchone will yield None as the pointer has already advanced past the only row in the result set.

检查数据是否存在的惯用sqlite方法是查询一行并测试其真实性-

The idiomatic sqlite way of checking if data exists, is to query a row, and test its truthiness -

result = cursor.fetchone()
if result:
    print(result)