您的位置:首页 > 编程语言 > Python开发

python中查询数据库时fetchone()函数和fetchall()函数的区别

2018-03-28 10:12 309 查看
我们在用python操作数据库的时候,经常会碰见两个函数:fetchone()和fetchall()
刚开始学习的时候可能会搞不清楚他们两个的区别
其实非常简单
首先fetchone()函数它的返回值是单个的元组,也就是一行记录,如果没有结果,那就会返回null
其次是fetchall()函数,它的返回值是多个元组,即返回多个行记录,如果没有结果,返回的是()
举个例子:cursor是我们连接数据库的实例
fetchone()的使用:
cursor.execute(select username,password,nickname from user where id='%s'  %(input)
result=cursor.fetchone();  此时我们可以通过result[0],result[1],result[2]得到username,password,nickname
fetchall()的使用:
cursor.execute(select * from user)
result=cursor.fetchall();此时select得到的可能是多行记录,那么我们通过fetchall得到的就是多行记录,是一个二维元组
((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))
备注:如果对元组的概念不是很理解,请看我的下一篇博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python fetchall