美文网首页
SQLite查询时fetchone()函数和fetchall()

SQLite查询时fetchone()函数和fetchall()

作者: 忘了呼吸的那只猫 | 来源:发表于2019-01-08 16:42 被阅读36次

我们在用python操作SQLite数据库的时候,经常会碰见两个函数: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))

相关文章

网友评论

      本文标题:SQLite查询时fetchone()函数和fetchall()

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