mysql fetchone_简述fetchone()函数

fetchone()函数报'NoneType' object is not subscriptable的错误今天有人向好程序员Python培训老师请教一道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只返回一维元组。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值