Skip to content
Computer ScienceCBSE Class 12 · Interface of Python with an SQL Database

INSERT, UPDATE and DELETE from Python: commit(), %s and format() (Class 12 Computer Science)

Updated 17 October 2026 · Fact-checked

To change a MySQL table from Python, run the INSERT, UPDATE or DELETE with cursor.execute() and then call con.commit() to save the change; rowcount gives the number of rows affected. Values from the user are inserted in the query with %s placeholders (cur.execute(query, values)) or with the string format() method.

INSERT, UPDATE and DELETE only change the table for good after con.commit(); rowcount tells how many rows were changed.

Illustration drawn for QuestionBuddy.

Understand INSERT, UPDATE and DELETE from Python: commit(), %s and format()

Statements that change data (INSERT, UPDATE, DELETE) need one extra step: **con.commit()**, which saves the change in the database. Without commit the change is not kept. Programs here use the STUDENT table (RollNo, Name, Class, Marks, City; five rows) of the database school, with con and cur already created.

INSERT with %s.

q = "INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)"
cur.execute(q, (6, "Tara", "12A", 82, "Pune"))
con.commit()
print(cur.rowcount, "record inserted")

Output: 1 record inserted. The values are given as a tuple, in the order of the columns. %s is used for numbers and text alike and needs no quotes around it.

The same with format().

rno, name, cls, marks, city = 6, "Tara", "12A", 82, "Pune"
q = "INSERT INTO STUDENT VALUES ({}, '{}', '{}', {}, '{}')".format(rno, name, cls, marks, city)

The query string becomes INSERT INTO STUDENT VALUES (6, 'Tara', '12A', 82, 'Pune'). With format() you must write the single quotes yourself around text and dates, or MySQL reports a syntax error.

UPDATE.

rno = int(input("Roll number: "))
new = int(input("New marks: "))
cur.execute("UPDATE STUDENT SET Marks = %s WHERE RollNo = %s", (new, rno))
con.commit()
print(cur.rowcount, "record updated")

For the inputs 3 and 85 the output is 1 record updated. If no row has that roll number, rowcount is 0.

DELETE.

cur.execute("DELETE FROM STUDENT WHERE City = %s", ("Pune",))
con.commit()
print(cur.rowcount, "record deleted")

On the original table this deletes Kiran and prints 1 record deleted. A one-value tuple needs a trailing comma: ("Pune",).

Safety note. The %s form passes values separately from the query, which protects the database from harmful input. Building a query by joining or formatting raw user text can be abused, so prefer %s in your own programs; format() is accepted in the syllabus.

Complete program shape. Import, connect, cursor, execute, commit, print rowcount, close.

INSERT, UPDATE and DELETE from Python: commit(), %s and format(): key facts

Saving changes
  • INSERT, UPDATE, DELETE need con.commit()
  • SELECT does not need commit
  • Without commit the change is lost
commit belongs to the connection, not the cursor.
The %s method
  • query = "... VALUES (%s, %s)"
  • cur.execute(query, values_tuple)
  • No quotes around %s
  • One value needs a trailing comma: (x,)
Values go in column order.
The format method
  • "... VALUES ({}, '{}')".format(a, b)
  • Quote text and dates inside the string
  • Print the final string to check it
A missing quote gives a syntax error.
rowcount
After INSERTrows inserted
After UPDATErows changed
After DELETErows removed
0 means no row matched
Print it for a confirmation message.

How to answer INSERT, UPDATE and DELETE from Python: commit(), %s and format() questions

Use this routine for any INSERT, UPDATE or DELETE program.

  1. 1Connect and create the cursor as usual.
  2. 2Read the values with input(); convert numbers with int() or float().
  3. 3Write the query with %s placeholders (or {} with format) and the WHERE condition for UPDATE and DELETE.
  4. 4Call cur.execute(query, tuple) and check that the tuple has one value per %s.
  5. 5Call con.commit(), then print cur.rowcount with a message.
  6. 6Close the connection; keep text values quoted when using format().

INSERT, UPDATE and DELETE from Python: commit(), %s and format() in real life

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

Admission desk

Suppose the admission desk types the details of a new student into a Python program that saves them to the STUDENT table.

Which method saves the record permanently, and what does rowcount show?

Try it first, then show the solutionSolution
  1. After execute, con.commit() writes the new record to the database.
  2. rowcount shows 1 because one row was inserted.

Answer: con.commit(); rowcount is 1.

Memory hook: Execute writes on the draft; commit signs and files it.

A marks correction

Suppose roll number 3 is found to have 85 marks instead of 79 and the teacher corrects it through a program.

Write the query and its values.

Try it first, then show the solutionSolution
  1. UPDATE with a WHERE on the roll number.
  2. cur.execute("UPDATE STUDENT SET Marks = %s WHERE RollNo = %s", (85, 3)); then commit.

Answer: UPDATE STUDENT SET Marks = 85 WHERE RollNo = 3, then con.commit().

Memory hook: Name the exact row with the primary key.

Tricks to remember INSERT, UPDATE and DELETE from Python: commit(), %s and format()

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

  • Change? Commit!

    Every change in data needs a commit; a SELECT does not.

    Use it when: When to call commit.

  • %s needs no quotes

    The placeholder handles quoting itself.

    Use it when: %s queries.

  • format needs your quotes

    Put single quotes around text and dates in the query string.

    Use it when: format() queries.

  • Comma for one

    A single-value tuple is written (x,).

    Use it when: DELETE with one value.

INSERT, UPDATE and DELETE from Python: commit(), %s and format(): solved examples

Ordered from board level to HOTS. Try each one before you open the solution.

Example 1: Saving the changes · 1 mark · MCQBoard level

Which method of the connection object saves the changes made by INSERT, UPDATE or DELETE?
(a) save() (b) commit() (c) execute() (d) close()

Try it first, then show the solutionSolution
  1. The word is commit.

Answer: (b) commit()

Example 2: Why commit · 2 marks · Short answerBoard level

Why is commit() needed after an INSERT statement executed from Python?

Try it first, then show the solutionSolution
  1. The execute() sends the change to the server, but it is not made permanent until it is committed. (1 mark)
  2. Without commit() the change is lost when the connection is closed. (1 mark)

Answer: commit() makes the change permanent in the database.

Example 3: Update with input · 3 marks · Short answerHarder board level

Write a program fragment (cursor ready) that reads a roll number and new marks from the user and updates the STUDENT table, then prints the number of records updated. Show the output for roll number 3 and marks 85.

Try it first, then show the solutionSolution
  1. rno = int(input("Roll number: "))
    new = int(input("New marks: "))
    cur.execute("UPDATE STUDENT SET Marks = %s WHERE RollNo = %s", (new, rno))
    con.commit()
    print(cur.rowcount, "record updated")
    (2 marks)
  2. For inputs 3 and 85 the output is: 1 record updated. (1 mark)

Answer: 1 record updated

Example 4: Insert with format() · 3 marks · Short answerHarder board level

Using the format() method, write code to insert the student (6, Tara, 12A, 82, Pune) into STUDENT, and write the query string that is produced.

Try it first, then show the solutionSolution
  1. q = "INSERT INTO STUDENT VALUES ({}, '{}', '{}', {}, '{}')".format(6, "Tara", "12A", 82, "Pune")
    cur.execute(q)
    con.commit()
    (2 marks)
  2. The string produced is INSERT INTO STUDENT VALUES (6, 'Tara', '12A', 82, 'Pune'). (1 mark)

Answer: INSERT INTO STUDENT VALUES (6, 'Tara', '12A', 82, 'Pune')

Example 5: Case: delete and verify · 4 marks · Case-basedHOTS / competency

Suppose the school removes the students of a city, then checks the table.

city = input("City to remove: ")
cur.execute("DELETE FROM STUDENT WHERE City = %s", (city,))
con.commit()
print(cur.rowcount, "record(s) deleted")
cur.execute("SELECT COUNT(*) FROM STUDENT")
print(cur.fetchone()[0])

(i) On the original table, what is printed for the input Delhi? (2 marks)
(ii) What is printed for the input Goa? (1 mark)
(iii) Why is the comma in (city,) needed? (1 mark)

Try it first, then show the solutionSolution
  1. (i) Delhi has two students (Asha, Joy), so 2 record(s) deleted; the table keeps 5 - 2 = 3 rows: output 2 record(s) deleted and then 3.
  2. (ii) No student is from Goa: 0 record(s) deleted, then the count remains 5.
  3. (iii) execute() expects a tuple (or list) of values; (city) is just a string, while (city,) is a one-element tuple.

Answer: (i) 2 record(s) deleted / 3 (ii) 0 record(s) deleted / 5 (iii) a one-element tuple needs the comma

Where students lose marks in INSERT, UPDATE and DELETE from Python: commit(), %s and format()

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

  • Mistake: Forgetting commit()

    The change is not saved permanently.

    Wrong working

    cur.execute(q, vals)
    con.close()

    Right working

    cur.execute(q, vals)
    con.commit()
    con.close()

    Do this: Write commit straight after execute for INSERT, UPDATE and DELETE.

    Usually costs: 1 mark

  • Mistake: Quoting %s

    The placeholder must stand alone; extra quotes break the query.

    Wrong working

    "... VALUES ('%s', %s)"

    Right working

    "... VALUES (%s, %s)"

    Do this: Remove quotes around %s.

    Usually costs: 1 mark

  • Mistake: Missing quotes with format()

    Text values need single quotes inside the query string.

    Wrong working

    "... VALUES ({}, {})".format(1, "Asha")

    Right working

    "... VALUES ({}, '{}')".format(1, "Asha")

    Do this: Check the printed query.

    Usually costs: 1 mark

  • Mistake: Calling commit on the cursor

    commit belongs to the connection object.

    Wrong working

    cur.commit()

    Right working

    con.commit()

    Do this: Use the connection name.

    Usually costs: 0.5 mark

Exam tips

  • Write con.commit() right after each execute that changes data and before close().
  • Prefer %s with a values tuple; remember the comma for a single value.
  • If you use format(), show the final query string in your answer.
  • Convert numeric input with int() or float() before using it.
  • Print cur.rowcount with a message to confirm how many records changed.

Practice questions on INSERT, UPDATE and DELETE from Python: commit(), %s and format()

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

    In the query "UPDATE STUDENT SET Marks = %s WHERE RollNo = %s", what does %s represent?
    (a) a comment (b) a placeholder for a value (c) a table name (d) a wildcard

    Hint

    The values are given in a tuple.

    Answer

    (b) a placeholder for a value

  2. Q2 · 1 mark · Very short answerBoard level

    Which attribute of the cursor gives the number of rows affected by a DELETE?

    Hint

    It is also used after fetching.

    Answer

    rowcount

  3. Q3 · 2 marks · Short answerHarder board level

    Write a statement to delete the record with roll number 5 using the format() method and commit the change.

    Hint

    A number needs no quotes.

    Answer

    cur.execute("DELETE FROM STUDENT WHERE RollNo = {}".format(5))
    con.commit()

  4. Q4 · 1 mark · Assertion-reasonHarder board level

    Assertion (A): In the format() method the text values must be enclosed in single quotes inside the query string.
    Reason (R): Without quotes MySQL reads the text as a column name or a syntax error occurs.
    (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.

    Hint

    Compare with %s.

    Answer

    (a) Both are true and R explains A.

  5. Q5 · 3 marks · Short answerHOTS / competency

    Suppose a program reads rno, name, cls, marks and city and inserts a record using %s. Write the full program (including the connection) and explain what is printed when the roll number already exists in the table.

    Hint

    The primary key rejects a duplicate.

    Answer
    import mysql.connector as m
    con = m.connect(host="localhost", user="root", passwd="pw", database="school")
    cur = con.cursor()
    rno = int(input("Roll: "))
    name = input("Name: ")
    cls = input("Class: ")
    marks = int(input("Marks: "))
    city = input("City: ")
    cur.execute("INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)", (rno, name, cls, marks, city))
    con.commit()
    print(cur.rowcount, "record inserted")
    con.close()

    If RollNo is the primary key and the number already exists, MySQL raises an integrity error (mysql.connector.Error) and the program stops before printing; wrap it in try-except to print a message instead.

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 method saves INSERT, UPDATE and DELETE?Show answer

    con.commit().

  2. 2.Which object does commit() belong to?Show answer

    The connection.

  3. 3.Is commit needed after SELECT?Show answer

    No.

  4. 4.What must wrap text values in the format() method?Show answer

    Single quotes inside the query string.

  5. 5.How is a one-value tuple written?Show answer

    (x,) with a trailing comma.

  6. 6.What does rowcount show after UPDATE?Show answer

    The number of rows changed.

INSERT, UPDATE and DELETE from Python: commit(), %s and format(): frequently asked questions

Why do we use commit() in Python MySQL connectivity?

INSERT, UPDATE and DELETE are made permanent in the database only after con.commit(); otherwise the change is lost when the connection closes.

What is the difference between %s and format() in queries?

%s is a placeholder filled by execute(query, values) and needs no quotes. format() builds the whole query string, so text and dates need single quotes written in the string.

What does cursor.rowcount give?

It gives the number of rows affected by INSERT, UPDATE or DELETE, or the number of rows retrieved by a SELECT after fetching.

What happens if I insert a duplicate primary key?

MySQL refuses the row and raises an error, so the program should catch mysql.connector.Error or check the key first.