difference between cursor and connection objects

Question:

I am confused about why python needs cursor object. I know jdbc and there the database connection is quite intuitive but in python I am confused with cursor object. Also I am doubtful about what is the difference between cursor.close() and connection.close() function in terms of resource release.

Asked By: Aman Deep Gautam

||

Answers:

Connection object is your connection to the database, close that when you’re done talking to the database all together. Cursor object is an iterator over a result set from a query. Close those when you’re done with that result set.

Answered By: John Gaines Jr.

The cursor paradigm is not specific to Python but are a frequent data structure in databases themselves.

Depending on the underlying implementation it may be possible to generate several cursors sharing the same connection to a database. Closing the cursor should free resources associated to the query, including any results never fetched from the DB (or fetched but not used) but would not eliminate the connection to the database itself so you would be able to get a new cursor on the same database without the need to authenticate again.

Answered By: Toote

As others mention, a Connection() is the network connection to the database, and it’s only real use is to return cursors. PEP-249, where DBApi 2.0 is specified, does not clearly define what exactly a connection or cursor is, nor what the close() method on each must do; only that
<module>.connect()
must return an instance of
<module>.Connection
, that
<module>.Connection.cursor()
must return an instance of
<module>.Cursor
, and
<module>.Cursor.execute()
should invoke the statement provided and return the resulting rows. In particular, it does not define a
<module>.Connection.execute()
, although specific implementations are free to implement them as extensions.

Depending on those extensions is probably unwise, though, since it means you won’t have as portable code. DBApi makes this two-level requirement because having an execute on the connection without an intermediate object can be difficult on some databases.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.