美文网首页
fetchone()函数报'NoneType' object i

fetchone()函数报'NoneType' object i

作者: 隐墨留白 | 来源:发表于2019-02-22 15:34 被阅读0次

    今天有人问我一道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,成功了,没报错了,可真不容易。
    还好,找了一篇文章,推荐一下
    关于python中的查询数据库内容中用到的fetchone()函数和fetchall()函数

    用法如下所示:
    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只返回一维元组。

    相关文章

      网友评论

          本文标题:fetchone()函数报'NoneType' object i

          本文链接:https://www.haomeiwen.com/subject/jskeyqtx.html