python的sqlite3需要使用游标cursor吗?

疑问:

1、connection.execute 和 cursor.execute 效果一样吗?效率一样吗?

2、用for row in cursor.fetchall() for  row in cursor 效果一样吗?

结论:

1、在sqlite3中是等效的,connection.execute的好处是更简洁。cursor.execute的好处是标准/通用(更换换其他数据库,代码无需调整,只需要改变import一行即可)

2、结果一样,但实现机制不一样。cursor.fetchall()的结果是一个list类型的对象,而cursor的结果不是list,但和list同样属于Iterable类型。

解惑参考:

https://stackoverflow.com/questions/6318126/why-do-you-need-to-create-a-cursor-when-querying-a-sqlite-database 

https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.execute   

https://docs.python.org/3/library/sqlite3.html#using-sqlite3-efficiently  

https://www.oschina.net/translate/few-tips-sqlite-perf  Getting the Most out of Sqlite3 with Python

https://stackoverflow.com/questions/21334767/is-sqlite3-fetchall-necessary 

https://stackoverflow.com/questions/17861152/cursor-fetchall-vs-listcursor-in-python

--------------------------------------------

python中使用sqlite,网上很多例子都会使用游标。解说是连接到数据库后,需要打开游标(Cursor),通过Cursor执行SQL语句,然后,获得执行结果。

conn = sqlite3.connect('test.db')
cursor = conn.cursor()
# 执行查询语句:
cursor.execute('select * from user where id=?', ('1',))
<sqlite3.Cursor object at 0x10f8aa340>
# 获得查询结果集:
values = cursor.fetchall()
values
[(u'1', u'Michael')]
cursor.close()
conn.close()

 但也有一些例子不使用游标,直接在connection上执行execute

如下图示例:

import sqlite3
 
conn = sqlite3.connect('mysql_person.db')
print "Opened database successfully";
 
cursor = conn.execute("SELECT id, name, address, salary from MT")
for row in cursor:
  print "ID = ", row[0]
  print "NAME = ", row[1]
  print "ADDRESS = ", row[2]
  print "SALARY = ", row[3], "\n"
 
print "Operation done successfully";
conn.close()

 既然connection就可以直接做的事情,为什么要加一个游标呢?

根据官方docsconnection.execute()非标准快捷方式,这个命令会创建一个中间游标对象,并调用游标对象的execute(),然后返回这个游标对象。

也就是他们实际上是等效的,connection.execute()在写法上更简洁一点。

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值