G
G
Gimli2012-01-27 19:14:27
MySQL
Gimli, 2012-01-27 19:14:27

Python + MySQLdb - why cursors?

Faced with the fact that in mysqldb there are two options for working - directly through the db object returned by MySQLdb.connect():

db.query(..)
# ...
db.store_result(..)

and through the cursor:
cursor = db.cursor()
cursor.execute(..)
cursor.fetchall() 
# etc.

Why is this and what is preferable to use?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin, 2012-01-27
@Norraxx

Yes, because this "cursor" is used in any way, only without your knowledge. I don’t know how it is created there or not, but it’s just that it is already fenced off from you.
The Cursor as such returns queries as a list of taps [(,...),...], but you can return the results as a dict() (DictCursor), or manipulate memory space in various ways (CursorStoreResultMixIn, CursorUseResultMixIn). There are also cursors on the server side (SSCursor, SSDictCursor), I don’t know how they work, but the manual says: “Use only if you are dealing with potentially large result sets.”.
If you do not want to brainwash yourself with what and how it works, use one cursor, at least because it is cleaner.

E
equand, 2012-01-28
@equand

Cursors are also good, because they are supposed to be interchangeable with other database drivers, i.e. business logic for changing from mysql to postgresql, etc. not that difficult to translate (in fact, they translated, sed replaced a couple of transactional and postgres-specific things, otherwise everything worked fine).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question