python的sqlite3需要使用游标cursor吗?
疑问:1、connection.execute 和 cursor.execute 效果一样吗?效率一样吗?2、用fetchall()和忽略fetchall效果一样吗? fetchone 和 limit 0,1 一样吗?结论:1、在sqlite3中是等效的,connection.execute的好处是更简洁。cursor.execute的好处是标准/通用(更换换其他数据库,代码无需调整,只需要改变i
疑问:
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://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)