Display records with fetchone() and fetchall() and count them with rowcount
Expt. No.26
Page No.52
fetchone(), fetchall() and rowcount
Aim
To write a Python program that displays records from a MySQL table using fetchone() and fetchall(), and shows the number of rows with rowcount.
Concepts used
Algorithm
- Connect to the database and create a cursor.
- Execute a SELECT query.
- fetchone() returns the first row; fetchall() returns the remaining rows.
- Display rowcount, the number of rows fetched so far.
- Run a second query with a condition and display its rows.
Program
# Fetching records: fetchone(), fetchall() and rowcount import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="your_password", database="school")cur = con.cursor()cur.execute("SELECT * FROM student") row = cur.fetchone()print("First record :", row)rest = cur.fetchall()print("Remaining records :")for r in rest: print(r)print("Rows fetched (rowcount):", cur.rowcount) cur.execute("SELECT name, marks FROM student WHERE marks > 75")data = cur.fetchall()print("Students above 75:", cur.rowcount)for r in data: print(r[0], r[1])con.close()
A marked line continues the line above it. In your file, write it on the same line.
Change your_password to your own MySQL password before you run it.
Table used
Table: student
+--------+-------+-------+ | rollno | name | marks | +--------+-------+-------+ | 1 | Asha | 82 | | 2 | Rohan | 67 | | 3 | Kabir | 91 | | 4 | Diya | 76 | | 5 | Neel | 58 | +--------+-------+-------+
Output
$ python pysql_fetch.py
First record : (1, 'Asha', 82)
Remaining records :
(2, 'Rohan', 67)
(3, 'Kabir', 91)
(4, 'Diya', 76)
(5, 'Neel', 58)
Rows fetched (rowcount): 5
Students above 75: 3
Asha 82
Kabir 91
Diya 76
✓ Printed by running this program, not typed by hand.
Result
fetchone() returned the first row (1, 'Asha', 82) and fetchall() the other four; rowcount was then 5. The second query returned the 3 students with marks above 75.
Viva voce: what the examiner may ask
01What does fetchone() return when no rows are left?
None.
02What does fetchall() return?
A list of tuples, one tuple per remaining row.
03What does rowcount give after a SELECT?
The number of rows fetched so far by that cursor.
Variations for the lab test
- Use
fetchmany(2)and see how it differs. (Not in the syllabus; for curiosity only.) - Display the topper's name using ORDER BY and fetchone().
- Display the records in a table-like format with headings.
! Common mistake Calling
fetchall() first and then fetchone() gives None, because fetchall() already read every row.