今天在练习python数据库的查询操作时,使用fetchone()、fetchMany()、fetchall()函数,出现了一些奇怪的现象,现在做如下记录。
我想在同一个代码块中,使用fetchone()查询一条信息,使用fetchmany(3)查询3条信息,fetchall()查询全部信息,查询的对应代码段如下:
#14.3 使用不同的方法查询用户信息
conn = sql.connect(r"D:\_spring\mirsoft.db")
cursor = conn.cursor()
cursor.execute('select * from user')
print("======fetchone()======")
result1 = cursor.fetchone()
print(result1)
print("======fetchmany()======")
result2 = cursor.fetchmany(3)
print(result2)
print("======fetchall()======")
result3 = cursor.fetchall()
print(result3)
cursor.close()
conn.commit()
conn.close()
然而并没有想要的结果。
#理想的结果
======fetchone()======
(1, 'Menny')
======fetchmany(3)======
[(1, 'Menny'), (2, 'Liming'), (3, 'Jydius')]
======fetchall()======
[(1, 'Menny'), (2, 'Liming'), (3, 'Jydius'), (4, 'spring')]
#实际的结果
======fetchone()======
(1, 'Menny')
======fetchmany()======
[(2, 'Liming'), (3, 'Jydius'), (4, 'spring')]
======fetchall()======
[]
原因:游标cursor如同C中文件的指针一样,每次都会移动到一定的位置,如果不指定它返回开头,那么就会沿着当前位置继续下一次的移动。所以,在以上代码中,fetchone得到的是第一个序号(1,“jenny”),紧接着的fetchmany(3)得到的是从第二个序号起的下面三个序号,即[(2, 'Liming'), (3, 'Jydius'), (4, 'spring')],再执行fetchall时,游标已经移动到了user表的末尾,没有记录可以查询,所以返回的是空值。
修改代码如下:
#14.3 使用不同的方法查询用户信息
conn = sql.connect(r"D:\_spring\spring_Python\exp_14_option_database\mirsoft.db")
cursor = conn.cursor()
cursor.execute('select * from user')
print("======fetchone()======")
result1 = cursor.fetchone()
print(result1)
print("\n======fetchmany(3)======")
cursor.execute('select * from user') #每一次都让游标返回user表的开头
result2 = cursor.fetchmany(3)
print(result2)
print("\n======fetchall()======")
cursor.execute('select * from user') #每一次都让游标返回user表的开头
result3 = cursor.fetchall()
print(result3)
cursor.close()
conn.commit()
conn.close()
得到如下结果:
======fetchone()======
(1, 'Menny')
======fetchmany(3)======
[(1, 'Menny'), (2, 'Liming'), (3, 'Jydius')]
======fetchall()======
[(1, 'Menny'), (2, 'Liming'), (3, 'Jydius'), (4, 'spring')]