bahman Shadmehr bahman Shadmehr - 1 year ago 85
MySQL Question

Avoid Cursor In Python

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)

Answer Source

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.