Skip to content
Computer ScienceCBSE Class 12 · Chapter 10

Interface of Python with an SQL Database: CBSE Class 12 Computer Science

Updated 14 October 2026 · Fact-checked

A Python program talks to MySQL through the mysql.connector module: connect() opens a connection, cursor() creates a cursor, execute() runs an SQL statement, commit() saves INSERT, UPDATE and DELETE changes, fetchone() and fetchall() read the results of a SELECT, and rowcount tells how many rows were fetched or changed. Values are passed with %s placeholders or format().

What Interface of Python with an SQL Database is about

Interface of Python with an SQL Database is the last chapter of Unit 3 (Database Management, 20 of 70 theory marks). It joins the two halves of the course: Python programs that store and read data in a MySQL table. In the 2026-27 sample paper it is a 4-mark Section D program (complete or write the code to insert, update or display records), and the practical exam's report file needs at least four Python-SQL connectivity programs.

The syllabus lists: connecting SQL with Python; performing insert, update and delete queries using a cursor; displaying data using connect(), cursor(), execute(), commit(), fetchone(), fetchall() and rowcount; creating database connectivity applications; and using the %s format specifier or format() to build queries. NCERT has no chapter on this topic, so this page follows the syllabus.

Every connectivity program follows six steps:
1. import mysql.connector (often as m or as sqltor)
2. open a connection with connect(host=..., user=..., passwd=..., database=...)
3. create a cursor with con.cursor()
4. run SQL with cur.execute(query) or cur.execute(query, values)
5. for SELECT, read rows with fetchone() / fetchall(); for INSERT, UPDATE or DELETE, save with con.commit()
6. close the connection with con.close()

The programs use a database school with this table:

STUDENT

RollNoNameClassMarksCity
1Asha12A88Delhi
2Ravi12B64Mumbai
3Meena12A79Chennai
4Joy12C91Delhi
5Kiran12B55Pune

Weightage: This chapter is part of Unit 3, Database Management, which carries 20 of the 70 theory marks together with Database Concepts and Structured Query Language (SQL).Source: CBSE Computer Science (083) syllabus 2026-27, distribution of marks, Unit 3 Database Management

Key concepts

Connecting Python with MySQL
NCERT section Not in NCERT; CBSE syllabus (connecting SQL with Python)

The mysql.connector module (installed with pip install mysql-connector-python) lets Python talk to a MySQL server. mysql.connector.connect() takes the server's host (usually 'localhost'), the MySQL user, the password (passwd or password) and, optionally, the database to use, and returns a connection object. con.is_connected() returns True if the connection succeeded. Always close the connection with con.close() at the end.

Worked example

Write code to connect to the database school on the local MySQL server with user root and password tiger, and print a message if the connection is open.

Try it first, then show the solutionSolution
  1. Import the module, call connect() with the four arguments, test is_connected().
  2. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    if con.is_connected():
        print('Connected to school')
    con.close()

Answer: Connected to school

Cursor and execute()
NCERT section Not in NCERT; CBSE syllabus (cursor(), execute())

A cursor is an object that runs SQL statements on the connection and holds the result of a SELECT so you can read it row by row. Create it with cur = con.cursor(). cur.execute(sql) sends one SQL statement as a string; cur.execute(sql, values) fills %s placeholders in the string with the values in a tuple (or list). One connection can have several cursors.

Worked example

Write the statements that create a cursor and select the names of students of class 12A.

Try it first, then show the solutionSolution
  1. Text in SQL needs quotes; the easiest safe way is a %s placeholder.
  2. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cur.execute('SELECT Name FROM STUDENT WHERE Class = %s', ('12A',))
    print(cur.fetchall())
    con.close()
  3. Note the comma in ('12A',): a one-item tuple.

Answer: [('Asha',), ('Meena',)]

Reading results: fetchone(), fetchall() and rowcount
NCERT section Not in NCERT; CBSE syllabus (fetchone(), fetchall(), rowcount)

After a SELECT, cur.fetchone() returns the next row as a tuple (or None when no rows are left); cur.fetchall() returns a list of tuples of all remaining rows (an empty list if none). Each fetch continues from where the last one stopped. cur.rowcount gives the number of rows fetched so far for a SELECT, and the number of rows affected for INSERT, UPDATE or DELETE. A single selected column still comes back as a tuple, e.g. ('Asha',).

Worked example

Predict the output:

import mysql.connector as m
con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
cur = con.cursor()
cur.execute('SELECT * FROM STUDENT WHERE Marks > %s', (70,))
r = cur.fetchone()
print(r, cur.rowcount)
rest = cur.fetchall()
print(rest, cur.rowcount)
con.close()
Try it first, then show the solutionSolution
  1. Rows with Marks > 70: Asha (88), Meena (79), Joy (91).
  2. fetchone() gives Asha's row; one row fetched so far.
  3. fetchall() gives the remaining two rows; three fetched in total.

Answer: (1, 'Asha', '12A', 88, 'Delhi') 1
[(3, 'Meena', '12A', 79, 'Chennai'), (4, 'Joy', '12C', 91, 'Delhi')] 3

INSERT, UPDATE and DELETE with commit()
NCERT section Not in NCERT; CBSE syllabus (insert, update, delete queries using cursor; commit())

Statements that change data are run with execute() like any other, but the change is only made permanent when you call **con.commit()** on the connection. Without commit(), the change is lost when the program ends (MySQL's tables use transactions). After the execute, cur.rowcount tells how many rows were inserted, updated or deleted, which is a quick way to report 'Record not found' when it is 0.

Worked example

Write code to add 5 marks to every student of class 12A, save the change and print how many records were updated.

Try it first, then show the solutionSolution
  1. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cur.execute('UPDATE STUDENT SET Marks = Marks + 5 WHERE Class = %s', ('12A',))
    con.commit()
    print(cur.rowcount, 'record(s) updated')
    con.close()
  2. Class 12A has Asha and Meena, so 2 rows change (88 → 93, 79 → 84).

Answer: 2 record(s) updated

Building queries with %s or format()
NCERT section Not in NCERT; CBSE syllabus (%s format specifier or format())

Values from variables can be put into a query in two ways. %s placeholders: write %s where each value goes (no quotes around it, even for text) and pass a tuple: cur.execute('INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)', (6, 'Neha', '12C', 72, 'Agra')). The connector adds quotes where needed. format(): build the full string yourself, putting quotes around text values: "INSERT INTO STUDENT VALUES ({}, '{}', '{}', {}, '{}')".format(6, 'Neha', '12C', 72, 'Agra'). Both are in the syllabus; %s is safer because the connector handles quoting.

Worked example

Insert the record (6, 'Neha', '12C', 72, 'Agra') using format(), commit it, and print the rowcount.

Try it first, then show the solutionSolution
  1. With format() the text values need their own single quotes inside the SQL string.
  2. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    q = "INSERT INTO STUDENT VALUES ({}, '{}', '{}', {}, '{}')".format(6, 'Neha', '12C', 72, 'Agra')
    cur.execute(q)
    con.commit()
    print(cur.rowcount)
    con.close()

Answer: 1

A complete database connectivity application
NCERT section Not in NCERT; CBSE syllabus (creating database connectivity applications)

A connectivity application wraps the six steps in functions: one to add a record, one to search, one to update, one to delete, one to display, often driven by a menu. Each function can open its own connection (simplest in exam answers) or share one. Read user input with input(), convert numbers with int(), pass values through %s, commit after changes, and report 'No such record' when rowcount is 0 or fetchone() returns None.

Worked example

Write a function search(roll) that prints the name and marks of the student with that roll number, or 'No such student'. Show search(3) and search(9).

Try it first, then show the solutionSolution
  1. import mysql.connector as m
    def search(roll):
        con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
        cur = con.cursor()
        cur.execute('SELECT Name, Marks FROM STUDENT WHERE RollNo = %s', (roll,))
        row = cur.fetchone()
        if row is None:
            print('No such student')
        else:
            print(row[0], row[1])
        con.close()
    search(3)
    search(9)
  2. RollNo 3 is Meena with 79 marks; RollNo 9 does not exist, so fetchone() gives None.

Answer: Meena 79
No such student

Interface of Python with an SQL Database in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

commit()

Suppose a school's fee app runs an UPDATE that marks Ravi's fee as paid, but the programmer forgets con.commit() and the app closes.

What will the accounts office see in the database the next day, and what one line fixes it?

Try it first, then show the solutionSolution
  1. Without commit(), the change belongs to an unfinished transaction and is discarded when the connection closes.
  2. Calling con.commit() after the execute() makes it permanent.

Answer: The fee still shows as unpaid; add con.commit() after the UPDATE.

Memory hook: No commit, no change: commit is the Save button.

rowcount for feedback

Imagine a librarian deletes a member by ID through a Python app and wants to know whether the ID existed.

How can the program tell, without another SELECT?

Try it first, then show the solutionSolution
  1. After cur.execute('DELETE FROM MEMBER WHERE MID = %s', (mid,)) and con.commit(), cur.rowcount gives the number of rows deleted.
  2. If it is 0, print 'No such member'; otherwise print 'Deleted'.

Answer: Check cur.rowcount after the DELETE: 0 means the ID was not found.

Memory hook: rowcount = how many rows the last command touched.

Fetching rows

Suppose a class teacher's app shows the top scorer first and then the rest of the class sorted by marks.

Write the code that prints the top scorer with fetchone() and then the rest with fetchall().

Try it first, then show the solutionSolution
  1. Sort in SQL, then take one row and then the remainder.
  2. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cur.execute('SELECT Name, Marks FROM STUDENT ORDER BY Marks DESC')
    top = cur.fetchone()
    print('Topper:', top[0], top[1])
    for name, marks in cur.fetchall():
        print(name, marks)
    con.close()

Answer: Topper: Joy 91
Asha 88
Meena 79
Ravi 64
Kiran 55

Memory hook: fetchone takes the first plate; fetchall takes the rest of the pile.

Topics in this chapter

Interface of Python with an SQL Database: syntax and key facts

Six steps
  1. 1.import mysql.connector
  2. 2.con = connect(host, user, passwd, database)
  3. 3.cur = con.cursor()
  4. 4.cur.execute(sql[, values])
  5. 5.fetch (SELECT) or con.commit() (INSERT/UPDATE/DELETE)
  6. 6.con.close()
commit() belongs to the connection, not the cursor.
Fetch methods
fetchone(): next row as a tuple or None; fetchall(): list of tuples of the remaining rows ([] if none)
Each fetch continues from where the previous one stopped.
rowcount
After SELECT: rows fetched so far. After INSERT/UPDATE/DELETE: rows affected.
It is an attribute: cur.rowcount, no brackets.
%s placeholders
cur.execute('... WHERE RollNo = %s AND City = %s', (roll, city))
No quotes around %s; a single value still needs a tuple: (roll,).
format()
"... VALUES ({}, '{}')".format(6, 'Neha')
Put quotes around text placeholders yourself.

How the board asks Interface of Python with an SQL Database

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Write a connectivity program (4 marks)Write a program or function to insert a record taken from the user, or to display records satisfying a condition, or to update/delete a record (Section D).Write all six steps; use %s with a tuple for values; commit after changes; print rows from fetchall() in a for loop.
Complete the code (fill the blanks)A program with blanks for the module name, the connect() call, the method that saves changes, the method that reads all rows (2-4 marks).Blanks are usually: mysql.connector, connect, cursor(), execute, commit(), fetchall() or fetchone(), rowcount.
Predict the outputA SELECT followed by fetchone()/fetchall() and prints of rows or rowcount on a given table (2 marks).Apply the query to the table first, then follow the fetch calls and remember rowcount accumulates.
Concept questionsRole of cursor; difference between fetchone() and fetchall(); why commit() is needed; what rowcount returns (1-2 marks).One-line definitions with the return type (tuple, list of tuples, integer).

Tricks to remember Interface of Python with an SQL Database

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • "I Can Cook Every Fine Curry"

    Import, Connect, Cursor, Execute, Fetch/commit, Close.

    Use it when: Writing all six steps in order.

  • Change → commit

    INSERT, UPDATE, DELETE change data, so they need commit(); SELECT only reads, so it needs a fetch.

    Use it when: Deciding between commit() and fetch.

  • One is a tuple, all is a list

    fetchone() → (row); fetchall() → [(row), (row)].

    Use it when: Output questions on fetch methods.

  • %s needs no quotes, {} needs quotes

    The connector quotes %s values for you; with format() you must quote text yourself.

    Use it when: Building queries without syntax errors.

Interface of Python with an SQL Database: board-level solved questions

Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: rowcount after mixed fetches · 2 marks · Short answerHOTS / competency

Predict the output:

import mysql.connector as m
con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
cur = con.cursor()
cur.execute('SELECT Name FROM STUDENT')
a = cur.fetchone()
b = cur.fetchone()
c = cur.fetchall()
print(a, b, len(c), cur.rowcount)
con.close()
Try it first, then show the solutionSolution
  1. Five names in table order. a = ('Asha',), b = ('Ravi',).
  2. fetchall() returns the remaining three rows.
  3. rowcount counts all rows fetched so far: 5.

Answer: ('Asha',) ('Ravi',) 3 5

Example 2: Fill in the blanks · 2 marks · Short answerBoard level

Complete the program that deletes students of Pune:

import ______ as m                              # (i)
con = m.______(host='localhost', user='root', passwd='tiger', database='school')   # (ii)
cur = con.cursor()
cur.execute('DELETE FROM STUDENT WHERE City = %s', ('Pune',))
con.______                                      # (iii)
print(cur.______, 'deleted')                     # (iv)
Try it first, then show the solutionSolution
  1. (i) mysql.connector (ii) connect (iii) commit() (iv) rowcount.
  2. Only Kiran lives in Pune, so 1 row is deleted.

Answer: (i) mysql.connector (ii) connect (iii) commit() (iv) rowcount; it prints 1 deleted.

Example 3: Assertion-reason on commit · 1 mark · Assertion-reasonHOTS / competency

Assertion (A): After cur.execute('INSERT ...') the new row may not appear in the table when checked from another session.
Reason (R): Changes made by INSERT are saved permanently only after con.commit() is called.
(a) Both true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true

Try it first, then show the solutionSolution
  1. Until commit(), the insert is part of an open transaction visible only to that connection.
  2. R gives exactly this reason.

Answer: (a) Both A and R are true and R is the correct explanation of A.

Example 4: Display with a condition and count · 4 marks · Long answerHarder board level

Write a program that displays the roll number, name and marks of students of Delhi, sorted by marks in descending order, and then the number of such students. Give the output.

Try it first, then show the solutionSolution
  1. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    city = 'Delhi'
    cur.execute('SELECT RollNo, Name, Marks FROM STUDENT WHERE City = %s ORDER BY Marks DESC', (city,))
    rows = cur.fetchall()
    for r in rows:
        print(r[0], r[1], r[2])
    print('Total:', cur.rowcount)
    con.close()
  2. Delhi students: Asha (88) and Joy (91); descending marks puts Joy first.

Answer: 4 Joy 91
1 Asha 88
Total: 2

Example 5: Update with format() · 3 marks · Short answerHarder board level

Using format() (not %s), write code that changes the city of the student named Ravi to 'Pune', saves it, and prints the rowcount. Then display Ravi's row.

Try it first, then show the solutionSolution
  1. With format(), text values must be quoted inside the SQL string.
  2. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    q = "UPDATE STUDENT SET City = '{}' WHERE Name = '{}'".format('Pune', 'Ravi')
    cur.execute(q)
    con.commit()
    print(cur.rowcount)
    cur.execute("SELECT * FROM STUDENT WHERE Name = '{}'".format('Ravi'))
    print(cur.fetchone())
    con.close()

Answer: 1
(2, 'Ravi', '12B', 64, 'Pune')

Example 6: Spot the errors · 2 marks · Short answerHOTS / competency

Find four errors:

import mysql.connector as m
con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
cur = con.cursor
cur.execute('INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)', (7, Tara, '12A', 81, 'Goa'))
cur.commit()
print(cur.rowcount())
Try it first, then show the solutionSolution
  1. cursor needs brackets: con.cursor().
  2. Tara is a string: 'Tara'.
  3. commit() belongs to the connection: con.commit().
  4. rowcount is an attribute: cur.rowcount without brackets.

Answer: con.cursor(); 'Tara'; con.commit(); cur.rowcount

Example 7: Which fetch? · 1 mark · MCQBoard level

A program needs only the highest marks: cur.execute('SELECT MAX(Marks) FROM STUDENT'). Which statement prints just the number 91? (a) print(cur.fetchall()) (b) print(cur.fetchone()) (c) print(cur.fetchone()[0]) (d) print(cur.rowcount)

Try it first, then show the solutionSolution
  1. fetchall() gives [(91,)]; fetchone() gives (91,).
  2. Indexing the tuple gives the number itself.

Answer: (c) print(cur.fetchone()[0])

Case-study practice (Section E style)

Read the situation, then answer every part. In the board paper this is a 4-mark question split into 1 + 1 + 2 marks.

Exam-result app

Suppose the examination cell uses the STUDENT table and a Python app built on mysql.connector. The app must show results, correct marks after re-evaluation and remove students who leave.

  1. (i) · 1 mark

    Which method of the connection object must be called after correcting marks?

    Answer

    Answer: commit()

    UPDATE changes data; commit() makes it permanent.

  2. (ii) · 1 mark

    What does cur.fetchone() return after cur.execute('SELECT Name FROM STUDENT WHERE Marks > 95') on this table?

    Answer

    Answer: None

    No student has more than 95 marks, so there is no row to fetch.

  3. (iii) · 2 marks

    Write code to raise Kiran's marks by 10 after re-evaluation, print the rowcount, and then display Kiran's name and marks.

    Answer

    Answer:

    import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cur.execute('UPDATE STUDENT SET Marks = Marks + 10 WHERE Name = %s', ('Kiran',))
    con.commit()
    print(cur.rowcount)
    cur.execute('SELECT Name, Marks FROM STUDENT WHERE Name = %s', ('Kiran',))
    print(cur.fetchone())
    con.close()
    Output:
    1
    ('Kiran', 65)

    One row is updated (55 → 65); the SELECT then reads the new value.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

Differentiate between fetchone() and fetchall(). [2 marks] (2 marks)

StepMarks
fetchone(): returns the next row of the result as a tuple, None if no row is left1
fetchall(): returns all remaining rows as a list of tuples (empty list if none)1

Write a function update_marks(roll, m) that sets the marks of the student with roll number roll to m and prints 'Updated' or 'Not found'. [3 marks] (3 marks)

StepMarks
Import, connect and create a cursor1
execute('UPDATE STUDENT SET Marks = %s WHERE RollNo = %s', (m, roll)) and con.commit()1
Checking cur.rowcount to print 'Updated' or 'Not found', and closing1

Write a program that displays the roll number, name and marks of all students of a city, with the city given in a variable, and the number of such students. [4 marks] (4 marks)

StepMarks
Import, connect and cursor1
SELECT with WHERE City = %s and the tuple (city,)1
fetchall() and a loop printing each row1
Printing cur.rowcount (or len of the list) and closing1

Write a menu-driven program with options 1 Add student, 2 Display all, 3 Delete by roll number, 4 Exit, using a MySQL table STUDENT. [5 marks] (5 marks)

StepMarks
Connection, cursor and the menu loop until 41
Option 1: input, INSERT with %s values, commit1
Option 2: SELECT * and fetchall() loop1
Option 3: DELETE with %s, commit and rowcount message1
Closing the connection; correct syntax throughout1

Where students lose marks in Interface of Python with an SQL Database

The slips examiners see most often, and what to write instead.

  • Mistake: Forgetting con.commit() after INSERT, UPDATE or DELETE

    The change is rolled back when the connection closes.

    Do this: Write con.commit() immediately after every execute() that changes data.

    Usually costs: 1 mark

  • Mistake: Calling commit() on the cursor

    commit() is a method of the connection object.

    Wrong working

    cur.commit()

    Right working

    con.commit()

    Do this: Remember: the connection saves; the cursor executes and fetches.

    Usually costs: Half to 1 mark

  • Mistake: Passing a single value without a tuple comma

    (70) is just the integer 70; execute() needs a sequence of values.

    Wrong working

    cur.execute('... WHERE Marks > %s', (70))

    Right working

    cur.execute('... WHERE Marks > %s', (70,))

    Do this: Write (value,) with the comma, or [value].

    Usually costs: Half a mark

  • Mistake: Putting quotes around %s or leaving them out with format()

    '%s' in quotes is inserted literally; format() does not add quotes for text.

    Wrong working

    "... WHERE Name = '%s'" with a values tuple, or "... WHERE Name = {}".format('Asha')

    Right working

    "... WHERE Name = %s" with (name,), or "... WHERE Name = '{}'".format('Asha')

    Do this: %s: never quote. format(): quote text placeholders.

    Usually costs: Half to 1 mark

  • Mistake: Printing the result of execute() instead of fetching

    execute() runs the query but does not return the rows; the rows are read with fetchone() or fetchall().

    Do this: After a SELECT, always call a fetch method and loop over its result.

    Usually costs: 1 mark

NCERT exercise guide: Interface of Python with an SQL Database

What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.

CBSE practical list: Python-SQL connectivity programs (report file needs at least four)

What it tests: Programs that insert, display, search, update and delete records of a MySQL table from Python (NCERT has no chapter on this topic).

How to approach it: Write each as a function with the six steps; test each with a known record.

Same kind as the report-file connectivity programs

Write add_student(rec) that inserts a record given as a tuple using %s placeholders, and then display the number of students in the table.

Show the solutionSolution
  1. import mysql.connector as m
    def add_student(rec):
        con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
        cur = con.cursor()
        cur.execute('INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)', rec)
        con.commit()
        cur.execute('SELECT COUNT(*) FROM STUDENT')
        print('Students now:', cur.fetchone()[0])
        con.close()
    add_student((6, 'Neha', '12C', 72, 'Agra'))
  2. The table had 5 students; after the insert, COUNT(*) is 6.

Answer: Students now: 6

CBSE practical list: display programs with conditions

What it tests: SELECT with a condition taken from a variable, reading rows and counting them.

How to approach it: Use %s for the condition value; loop over fetchall(); use rowcount for the count.

Same kind as the display programs

Display the name and marks of students of a given class ('12B'), then the number of records displayed.

Show the solutionSolution
  1. import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cls = '12B'
    cur.execute('SELECT Name, Marks FROM STUDENT WHERE Class = %s', (cls,))
    for row in cur.fetchall():
        print(row[0], row[1])
    print('Records:', cur.rowcount)
    con.close()

Answer: Ravi 64
Kiran 55
Records: 2

Practice questions on Interface of Python with an SQL Database

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · MCQBoard level

    Which method returns all the remaining rows of a query result? (a) fetchone() (b) fetchall() (c) execute() (d) commit()

    Hint

    List of tuples.

    Answer

    (b) fetchall()

  2. Q2 · 1 mark · Very short answerBoard level

    What is a cursor in Python-MySQL connectivity?

    Hint

    It executes and holds results.

    Answer

    An object created from the connection that executes SQL statements and holds the result set so rows can be fetched.

  3. Q3 · 2 marks · Short answerHarder board level

    Predict the output:

    import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cur.execute('SELECT Name, Marks FROM STUDENT WHERE Class = %s', ('12A',))
    for n, mk in cur.fetchall():
        print(n, mk + 2)
    print(cur.rowcount)
    con.close()
    Hint

    Two students in 12A.

    Answer

    Asha 90
    Meena 81
    2

  4. Q4 · 2 marks · Short answerBoard level

    Write the statement that inserts the values in the variables r, n, c, mk and ct into STUDENT using %s, and the statement that saves it.

    Hint

    Five placeholders, one tuple.

    Answer

    cur.execute('INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)', (r, n, c, mk, ct))
    con.commit()

  5. Q5 · 1 mark · Assertion-reasonHOTS / competency

    Assertion (A): cur.execute('SELECT * FROM STUDENT WHERE RollNo = %s', (3)) raises an error.
    Reason (R): The values for %s placeholders must be given as a sequence such as a tuple, and (3) is an int.

    Hint

    What is (3)?

    Answer

    (a) Both A and R are true and R is the correct explanation of A; write (3,).

  6. Q6 · 3 marks · Short answerHarder board level

    Write a function delete_student(roll) that deletes the student with the given roll number and prints 'Deleted' or 'No such roll number'. Show the output of delete_student(5) followed by delete_student(5).

    Hint

    Use rowcount after the DELETE.

    Answer
    import mysql.connector as m
    def delete_student(roll):
        con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
        cur = con.cursor()
        cur.execute('DELETE FROM STUDENT WHERE RollNo = %s', (roll,))
        con.commit()
        if cur.rowcount == 0:
            print('No such roll number')
        else:
            print('Deleted')
        con.close()
    delete_student(5)
    delete_student(5)

    Output:
    Deleted
    No such roll number

  7. Q7 · 3 marks · Short answerHOTS / competency

    Write a program to display the average marks of each class using GROUP BY from Python, one class per line.

    Hint

    The SQL does the grouping; Python only prints.

    Answer
    import mysql.connector as m
    con = m.connect(host='localhost', user='root', passwd='tiger', database='school')
    cur = con.cursor()
    cur.execute('SELECT Class, AVG(Marks) FROM STUDENT GROUP BY Class ORDER BY Class')
    for cls, avg in cur.fetchall():
        print(cls, round(avg, 1))
    con.close()

    Output:
    12A 83.5
    12B 59.5
    12C 91.0
    (MySQL returns AVG as a Decimal; round() still works.)

  8. Q8 · 2 marks · Short answerHOTS / competency

    Why is it better to pass values with %s than to join strings with +, for example 'SELECT * FROM STUDENT WHERE Name = ' + name?

    Hint

    Quotes and safety.

    Answer

    With + you must add the quotes yourself, and a name containing a quote (e.g. O'Neil) breaks the query; a user could also type SQL that changes the meaning of the query. With %s the connector quotes and escapes the value correctly.

  9. Q9 · 1 mark · Very short answerHarder board level

    What will print(con.is_connected()) show after con.close()?

    Hint

    The connection is closed.

    Answer

    False

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.Which module connects Python with MySQL in the syllabus?Show answer

    mysql.connector.

  2. 2.Which method creates the object that executes SQL statements?Show answer

    cursor() of the connection object.

  3. 3.What does fetchone() return when no rows are left?Show answer

    None.

  4. 4.What type does fetchall() return?Show answer

    A list of tuples.

  5. 5.Why is commit() needed?Show answer

    To make INSERT, UPDATE and DELETE changes permanent in the database.

  6. 6.What does cur.rowcount give after an UPDATE?Show answer

    The number of rows updated (affected).

  7. 7.Which method checks whether a connection was made?Show answer

    is_connected() of the connection object.

  8. 8.Name the two ways to put Python values into a query in the syllabus.Show answer

    The %s format specifier (with a tuple of values) and str.format().

Best order to study it

  1. The six steps and the role of each object (connection, cursor).
  2. connect() arguments and is_connected().
  3. SELECT with fetchone() and fetchall(); rowcount after fetching.
  4. INSERT, UPDATE, DELETE with commit() and rowcount.
  5. %s placeholders and format(), with quoting rules.
  6. Write complete functions: add, search, update, delete, display; then a menu.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • import mysql.connector; con = mysql.connector.connect(host=..., user=..., passwd=..., database=...).
  • cur = con.cursor(); cur.execute(sql) or cur.execute(sql, values).
  • fetchone(): next row as a tuple or None; fetchall(): list of tuples.
  • rowcount: rows fetched so far (SELECT) or rows affected (INSERT/UPDATE/DELETE).
  • con.commit() after any change; con.close() at the end.
  • %s placeholders take a tuple and need no quotes; (x,) for one value.
  • format() needs quotes around text values in the SQL string.
  • A one-column row is still a tuple: ('Asha',).

Interface of Python with an SQL Database: frequently asked questions

Is this chapter in the NCERT book?

No. The NCERT Class XII book has no chapter on Python-MySQL connectivity. The topic comes from the CBSE syllabus, which lists connect(), cursor(), execute(), commit(), fetchone(), fetchall(), rowcount and the %s or format() method.

Is fetchmany() in the syllabus?

It is not named in the 2026-27 list, which mentions fetchone() and fetchall(). Answer with those two unless a question specifically uses fetchmany().

How many marks does Python-SQL connectivity carry?

It is part of Unit 3 (20 of 70 theory marks). In the 2026-27 sample paper it appears as a 4-mark Section D program. The practical report file must also contain at least four Python-SQL connectivity programs.

Should I write passwd or password in connect()?

Both are accepted by mysql.connector. Textbooks and board answers often use passwd; use whichever you have practised, consistently.

Do I need to close the cursor and the connection?

Closing the connection with con.close() is expected in answers. Closing the cursor (cur.close()) is good practice but is not required by the syllabus.

Based on: CBSE Computer Science (083) syllabus 2026-27; NCERT Computer Science, Textbook for Class XII (Reprint 2026-27)