We have discussed how to create, connect and insert into the database so far.Please read the previous articles to start.
- Read: How To Create MYSQL Database using PHPMyAdmin and Shell
- Read: How To Connect To The MYSQL Database Using Python
- Read: How To Insert Data Into Mysql Database Using Python
Get Data From MYSQL Database Using Python
I give the simple documentation in the code only.Because I already explained clearly in the previous articles about how this code works.
In this code cur.fetchall() is something you may not aware of.If you see the above output image you can get this very easily it just fetches all your data into python lists that contain tuples.
Now you can get your data as you wish.
print row #This will print the first tuple of your data
print row #This will print the first element in the First Tuple (prathap)
If you didn’t understand this, please read about python lists and tuples.
Typical MYSQL Fetch Methods In Python
We are going to use these two fetch functions to retrieve our data.If you replace the Fetchall() function with fetchone() function you will get a list that contains a single tuple only because it fetches only one row and waits to fetch the next one.
But If your table has the many columns, then it will be hell to understand the data.So we should print the data line by line somewhat professionally 😛 (not much)
Here we are using While loop to make sure row is not empty.This data will be printed only if the row is not empty.
We don’t know how many rows will be there so that we are using len(row) to find the length.
So Every row will be printed line by line up to its range.
After iterating through all the rows, finally, our while loop will be terminated.
We can achieve this easily with the fetchone() method.
Unlike in the last method where all the fetched rows (list of tuples) assigned to a row variable, In this method, we are just fetching one row (a single tuple).So probably row is not an empty then our while loop iterates the row ( Now It prints the first row).
Now we have to get the next row.Here What the fetchone() does exactly for us.It fetches the next row and assigned to the row variable.So the loop iterates in itself only until the rows are empty.
Assume that what If we are not given the row = cur.fetchone() in the while loop ???
OOPS It goes to Infinite Loop 😛 Because, as there is no empty row, it loops always.
Hope you enjoy the article.Please read and practice 🙂
Please, Like Our Facebook Page For More Updates and Comment Here.