fetchone() 函数报 'NoneType' object is not subscriptable 的错误今天有人向我 请教一道 python 操作 mysql 的题,我也是差一点掉坑里去了。题是这样的: python 操作数据库,实现用户的注册登陆功能。其中最主要的是数据库的存入和读取。
其中一段代码如下:
# 查询与用户名对应的密码
sql = "select hash_password from user where username ='{}'".format(self.username)
self.cursor.execute(sql)
# 输出查询结果
print(self.cursor.fetchone()[0])
print(self.passwd)
# 对比,查询结果与加密后的密码
if self.cursor.fetchone()[0] == self.passwd:
print(' 登录成功 ')
else:
print(' 请输入正确的密码 ')
乍一看没什么错,但是执行报错了,
e10adc3949ba59abbe56e057f20f883e
e10adc3949ba59abbe56e057f20f883e
rl.login()
File "xxxxxx", line 314,in login
if self.cursor.fetchone()[0] == self.passwd:
TypeError: 'NoneType' object is not subscriptable
怎么回事呢?明明输出的两个密码是一样的,怎么对比出错呢,而且报错也很奇怪,NoneType 说明对比的两个值中有一个是 None , self.passwd 排除,那只能说 self.cursor.fetchone()[0] 是 None ,我将 if 注释了,再次 print() 输出一下 self.cursor.fetchone()[0] ,果然又报错了
print(self.cursor.fetchone()[0])
TypeError: 'NoneType' object is not subscriptable
这下捉急了,百度呗,查了半天也没查到什么。过了一会才想起如果mysql 执行语句结果的查询集只有一行数据,是不能调用两次 self.cursor.fetchone() 的,也就是说,第二次调用根本不可能有结果。那我把代码改一下好了。
sql = "select hash_password from user where username ='{}'".format(self.username)
self.cursor.execute(sql)
sql_password = self.cursor.fetchone()[0]
print(sql_password)
print(self.passwd)
if sql_password == self.passwd:
print(' 登录成功 ')
else:
print(' 请输入正确的密码 ')
OK ,成功了,没报错了,可真不容易。
用法如下所示:
fetchone() 用法:
cur.execute("select host,user,password from user where user='%s'" %acc)
jilu = cur.fetchone() ## 此时 通过 jilu[0],jilu[1],jilu[2] 可以依次访问 host,user,password
fetchall() 用法:
cur.execute("select * from user")
如果select 本身取的时候有多条数据时:
cursor.fetchone() :将只取最上面的第一条结果,返回单个元组如 ('id','title') ,然后多次使用 cursor.fetchone() ,依次取得下一条结果,直到为空。
cursor.fetchall() : 将返回所有结果,返回二维元组,如 (('id','title'),('id','title')),
如果select 本身取的时候只有一条数据时:
cursor.fetchone() :将只返回一条结果,返回单个元组如 ('id','title') 。
cursor.fetchall() : 也将返回所有结果,返回二维元组,如 (('id','title'),),
备注:其中的id 和 title 为具体的内容
python 在 mysql 在使用 fetchall 或者是 fetchone 时,综合起来讲, fetchall 返回二维元组(元组中含有元组), fetchone 只返回一维元组。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69913864/viewspace-2731258/ ,如需转载,请注明出处,否则将追究法律责任。