Python Practice › SQLite Programs › Program 5
Update rows
Write a Python program to add 5 bonus marks to students below 80.
Output
updated: 2
[('Asha', 91), ('Ravi', 79), ('John', 70)]Approach
UPDATE ... SET marks = marks + 5 WHERE ...;rowcounttells how many rows changed.
Solution
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (name TEXT, marks INTEGER)")conn.executemany("INSERT INTO students VALUES (?, ?)", [("Asha", 91), ("Ravi", 74), ("John", 65)])cur = conn.execute("UPDATE students SET marks = marks + 5 WHERE marks < 80")print("updated:", cur.rowcount)print(conn.execute("SELECT * FROM students").fetchall())Output
updated: 2
[('Asha', 91), ('Ravi', 79), ('John', 70)]Learn the concept
New to this topic? Read the lesson, then come back.