python 使用sqlite需要使用游标cursor?
在大多数情况下,很多在线文档示例中都会使用游标,为什么需要游标(cursor)管理?
connection = sqlite3.connect(':memory:') cursor = connection.cursor() # Do something with cursor
该写法是把sqlite存储内存中使用。
但是在大多数情况下,您根本不需要游标,并且可以直接使用该connection对象(在文档结尾处提到了该对象)。
比如execute和操作executemany可以直接在连接上调用,调用成功后并返回一个游标cursor。如下图示例:
import sqlite3 connection = sqlite3(':memory:') # Create a table connection.execute('CREATE TABLE events(ts, msg)') # Insert values connection.executemany( 'INSERT INTO events VALUES (?,?)', [ (1, 'foo'), (2, 'bar'), (3, 'baz') ] ) # Print inserted rows for row in connection.execute('SELECT * FROM events'): print(row)
游标(cursor)可以迭代
你可能会经常看得到一些示例,使用select查询结果中使用fetchone或者fetchall。但是我发现,使用结果最自然的方法是直接在游标上迭代。
for row in connection.execute('SELECT * FROM events'): print(row)
这样,你就可以在得到足够的结果后立即停止,而不会浪费资源。当然,如果事先知道需要多少结果,可以使用limit sql语句,但是Python生成器非常方便,可以将数据生成与数据消耗分离开来。
还没有留言,还不快点抢沙发?