Sqlite 作为一种体积小巧却功能强大的数据库,广泛应用在各种操作系统和平台上,比如在我熟悉的 iOS 平台,sqlite 几乎是各个大厂 app 用来持久化的首选,就连 Apple 主推的 CoreData 也主要使用 sqlite 作为底层引擎。Python 3 的标准库里也自带 sqlite 包,方便开发者使用。Python 3 下如何操作 sqlite 暂且不表,这里只说说 CursorConnection 这两个类联系与区别。

一般意义上的 Cursor

查询 Wikipedia 可知:

In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator. … A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only reference one row at a time, but can move to other rows of the result set as needed.


一个数据库的 cursor(游标)是用来遍历数据库记录的控制结构。它用来检索、插入和删除数据,以及后续的操作。这些特性使得它很像编程语言里迭代器的概念。


Python sqlite3 里的 Cursor

而在 Python sqlite3 里,当使用:

connection = sqlite3.connect("/path/to/your.db")


cursor = connection.cursor()

获得一个 cursor 对象。通过查看文档可以知道:

connection 和 cursor 对象都有 execute 这个主要的操作方法


Connection.execute(sql[, parameters]) This is a nonstandard shortcut that creates a cursor object by calling the cursor() method, calls the cursor’s execute() method with the parameters given, and returns the cursor.

Using the nonstandard execute(), executemany() and executescript() methods of the Connection object, your code can be written more concisely because you don’t have to create the (often superfluous) Cursor objects explicitly. Instead, the Cursor objects are created implicitly and these shortcut methods return the cursor objects. This way, you can execute a SELECT statement and iterate over it directly using only a single call on the Connection object.


Connection 对象的 execute 方法,是通过创建一个 cursor 中间对象,并调用这个 cursor 对象的 execute 方法,并返回这个 cursor 对象。它有助于使代码更加简洁清晰。


由上面的分析可知,Python sqlite3 包里的 connection 用来进行打开/关闭数据库、提交结果到数据库,虽然 connection 也有 execute 方法用来执行 SQL 语句,但主要是通过生成一个中间变量的方式,最终还是要通过 cursor 对象来执行。