1

I'm new in python and mysql. I'm trying to understand how to connect to a mysql database. so far, i know that i can use pymysql and make a cursor object. But I really can't figure out the point of cursor. So I have three questions.
What exactly a cursor is and why should I use it?
I've heard that it's better to avoid cursor. Why?
How can I use a mysql database without cursor?(I've searched and found nothing. I think the reason is that I don't know what should I search)

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
  • 1
    http://stackoverflow.com/questions/6318126/why-do-you-need-to-create-a-cursor-when-querying-a-sqlite-database – iScrE4m Sep 11 '16 at 16:36

1 Answers1

6

Your question is rather broad but it does bring up an important distinction in language. There is a difference between the way that Python (as well as other languages that interface to databases) uses cursors and what is meant by "avoid using cursors".

When you run a SELECT query, then the result set needs to be returned somehow to the calling application. Many interfaces provide a cursor interface to this result set. That is fine. This is simply the interface to the result set.

The warning against using cursors is when you continue the data processing (for anything other than formatting purposes) with the cursor. A particularly bad situation is when you have loops with multiple cursors doing the processing. There is an acronym for this type of processing: RBAR, which stands for "row by agonizing row".

In Python, you do not need a cursor interface into the database. You can also directly load the data into a data structure, such as a dataframe using pandas/numpy or some other module.

If your purpose is to learn Python, then Pandas/Numpy is good to learn. If your purpose is to learn SQL, then either the cursor interfaces or the modules that load into data frame are probably fine.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I would just add, if you know your sql, and your purpose is to learn better ways to use databases with Python, it would be good to learn sqlalchemy. – zvone Sep 11 '16 at 19:45