Worksheets › Class 12 › Interface Python with MySQL › Cheat sheet

Class 12 Interface Python with MySQL: cheat sheet

CBSE Computer Science. Connecting Python to MySQL: connect(), cursor(), execute(), commit(), fetchone(), fetchall() and rowcount, with %s placeholders and format().

Open the printable cheat sheetPractice worksheet

Key ideas

Remember

The stepsimport → connect() → cursor() → execute() → fetchone() or fetchall() → close()
A query with a valueq = 'SELECT Name FROM STUDENT WHERE Marks > %s' cur.execute(q, (80,)) for row in cur.fetchall():     print(row[0])
One valuethe tuple (80,) needs its comma
format()"SELECT * FROM STUDENT WHERE Marks > {}".format(m)
Saving a changecur.execute(an UPDATE), then con.commit(); cur.rowcount = rows changed
After fetchall()len(rows) equals cur.rowcount; fetchone()[0] is the first column of a row

Watch out

Worked example

Table: STUDENT RollNo | Name | Sec | City | Marks 201 | Priya | C | Delhi | 58 202 | Meera | C | Delhi | 76 203 | Ananya | B | Indore | 69 204 | Rahul | C | Delhi | 80 205 | Kabir | C | Jaipur | 65 206 | Isha | C | Jaipur | 94 207 | Rohan | C | Indore | 41 The program runs cur.execute("SELECT Name, Marks FROM STUDENT WHERE Marks BETWEEN 58 AND 80 ORDER BY Marks DESC"), then calls cur.fetchone() 3 times, then data = cur.fetchall(). What is len(data)?

Working: 5 rows in the result; 3 already fetched

Answer: 2

Practise Interface Python with MySQL

Revise with this page, then practise: every Interface Python with MySQL sheet in the app is new, with an answer key and working.

Coming soon for Android and iPhone.