fetchone()函数报'NoneType'objectisnotsubscriptable的错误。今天有人请教好的程序员Python培训老师一道python操作mysql的题,差点掉坑里。问题是这样的:Python操作数据库实现用户的注册登录功能。其中最重要的是数据库的存储和读取。其中一段代码如下:查询用户名对应的密码sql="selecthash_passwordfromuserwhereusername='{}'".format(self.username)self.cursor.execute(sql)输出查询结果print(self.cursor.fetchone()[0])print(self.passwd)将查询结果与加密后的密码进行比较ifself.cursor.fetchone()[0]==self.passwd:print('登录成功')else:print('请输入正确的密码')乍一看没什么问题,但是执行报错,e10adc3949ba59abbe56e057f20f883erl.login()File"xxxxxx",line314,inloginifself.cursor.fetchone()[0]==self.passwd:TypeError:'NoneType'objectisnotsubscriptable怎么了?明明两次输出的密码是一样的,怎么会比较错误,而且错误也很奇怪,NoneType表示比较中的两个值之一是None,self.passwd是排除了,所以只能说self.cursor.fetchone()[0]是None,我把if注释了,又打印了()输出self.cursor.fetchone()[0],果然,一个errorwasreportedprint(self.cursor.fetchone()[0])TypeError:'NoneType'objectisnotsubscriptable这个急,百度呗,找了半天也没找到。过了一会儿,我想起来如果mysql执行语句的结果查询集只有一行数据,self.cursor.fetchone()不能调用两次,也就是说第二次调用是不可能有一个结果。然后我会更改代码。sql="selecthash_passwordfromuserwhereusername='{}'".format(self.username)self.cursor.execute(sql)sql_password=self.cursor.fetchone()[0]print(sql_password)print(self.passwd)ifsql_password==self.passwd:print('登录成功')else:print('请输入正确的密码')OK,成功了,没有报错,真是不容易。用法如下:fetchone()usage:cur.execute("selecthost,user,passwordfromuserwhereuser='%s'"%acc)jilu=cur.fetchone()##passjilu[0]at这时候jilu[1],jilu[2]可以依次访问host,user,passwordfetchall()用法:cur.execute("select*fromuser")select本身fetch时如果有多个数据:cursor.fetchone():只取topfirst的结果,返回单个元组如('id','title'),然后多次使用cursor.fetchone()依次获取下一个结果直到它是空的。cursor.fetchall():会返回所有的结果,如果只有一个则返回一个二维元组,如(('id','title'),('id','title'))获取select本身时的数据:cursor.fetchone():将只返回一个结果,返回单个元组,例如('id','title')。cursor.fetchall():同样会返回所有结果,返回一个二维元组,如(('id','title'),),注意:id和title是具体内容。Python在使用fetchall或fetchone时,一般来说,fetchall返回的是二维元组(元组中包含元组),而fetchone只返回一维元组。
