ByteBoard Notes Notes

Update a record in a MySQL table from Python using format()

Computer Science XII · Experiment 27 of 29 · SQL

12-CSPython–SQL connectivity
Expt. No.27
Page No.54

Update a record with format()

Aim

To write a Python program that updates the marks of a student whose roll number is entered by the user, building the query with format().

Concepts used

Algorithm

  1. Input the roll number and the new marks.
  2. Build the UPDATE query with format() and execute it.
  3. Call commit().
  4. If rowcount is 0, display "No such roll number"; otherwise display the updated record.

Program

# Update a record using format() import mysql.connector con = mysql.connector.connect(host="localhost", user="root",                              password="your_password", database="school")cur = con.cursor() roll = int(input("Enter the roll number: "))marks = int(input("Enter the new marks  : "))query = "UPDATE student SET marks = {} WHERE rollno = {}".format(marks, roll)cur.execute(query)con.commit() if cur.rowcount == 0:    print("No such roll number")else:    print(cur.rowcount, "record updated")    cur.execute("SELECT * FROM student WHERE rollno = {}".format(roll))    print(cur.fetchone())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

Run 1
$ python pysql_update.py
Enter the roll number: 5 Enter the new marks : 64 1 record updated (5, 'Neel', 64)
Run 2
$ python pysql_update.py
Enter the roll number: 9 Enter the new marks : 70 No such roll number

✓ Printed by running this program, not typed by hand.

Result

Roll number 5 (Neel) was updated from 58 to 64 marks and rowcount was 1. Roll number 9 does not exist, so rowcount was 0 and the program said so.

Viva voce: what the examiner may ask

01What does rowcount give after UPDATE?

The number of rows changed by the statement.

02What do the {} in the query string do?

format() replaces them, in order, with the values passed to it.

03Why are quotes needed around string values when using format()?

SQL needs strings in quotes, e.g. "... WHERE name = '{}'".format(name); numbers don't need them.

Variations for the lab test

  1. Update a student's name, remembering the quotes.
  2. Increase the marks of every student by 5 and display rowcount.
  3. Rewrite the query with %s placeholders.
! Common mistake Checking rowcount before execute(), or forgetting commit(), gives a wrong message or a change that is not saved.
Back to the 12-CS index