HomeComputer SciencePracticalClass 12Update Records

Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

INTERFACING PYTHON WITH MYSQL - UPDATE RECORDS

AIM

To write a Python program to interface with MySQL database and update existing records in a table based on specific conditions.

ALGORITHM

  1. Start
  2. Import mysql.connector module
  3. Establish connection to MySQL database
  4. Create cursor object
  5. Display all records before update
  6. Accept record ID to update from user
  7. Accept new values for fields to update
  8. Execute UPDATE query with WHERE clause
  9. Commit the transaction
  10. Display confirmation message
  11. Display updated records
  12. Close cursor and connection
  13. Stop

PROGRAM

# Python program to update records in MySQL database

import mysql.connector

def connect_database():
    """Establish connection to MySQL database"""
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='school',
            user='root',
            password='password'
        )
        return connection
    except mysql.connector.Error as error:
        print(f"Error connecting to MySQL: {error}")
        return None

def display_records(cursor):
    """Display all records from students table"""
    cursor.execute("SELECT * FROM students")
    records = cursor.fetchall()
    
    if records:
        print("\n--- Student Records ---")
        print("ID\tName\t\tAge\tGrade")
        print("-" * 40)
        for record in records:
            print(f"{record[0]}\t{record[1]:<12}\t{record[2]}\t{record[3]}")
    else:
        print("No records found in the table.")

def update_records():
    """Main function to update records"""
    connection = connect_database()
    
    if connection is None:
        return
    
    cursor = connection.cursor()
    
    try:
        # Display records before update
        print("Records before update:")
        display_records(cursor)
        
        # Get student ID to update
        student_id = input("\nEnter Student ID to update: ")
        
        # Check if student exists
        cursor.execute("SELECT * FROM students WHERE id = %s", (student_id,))
        student = cursor.fetchone()
        
        if not student:
            print("Student with given ID not found!")
            return
        
        print(f"\nCurrent details: ID={student[0]}, Name={student[1]}, Age={student[2]}, Grade={student[3]}")
        
        # Get what to update
        print("\nWhat do you want to update?")
        print("1. Name")
        print("2. Age")
        print("3. Grade")
        print("4. All fields")
        
        choice = input("Enter your choice (1-4): ")
        
        if choice == '1':
            new_name = input("Enter new name: ")
            query = "UPDATE students SET name = %s WHERE id = %s"
            values = (new_name, student_id)
        elif choice == '2':
            new_age = input("Enter new age: ")
            query = "UPDATE students SET age = %s WHERE id = %s"
            values = (new_age, student_id)
        elif choice == '3':
            new_grade = input("Enter new grade: ")
            query = "UPDATE students SET grade = %s WHERE id = %s"
            values = (new_grade, student_id)
        elif choice == '4':
            new_name = input("Enter new name: ")
            new_age = input("Enter new age: ")
            new_grade = input("Enter new grade: ")
            query = "UPDATE students SET name = %s, age = %s, grade = %s WHERE id = %s"
            values = (new_name, new_age, new_grade, student_id)
        else:
            print("Invalid choice!")
            return
        
        # Execute update query
        cursor.execute(query, values)
        
        if cursor.rowcount > 0:
            connection.commit()
            print(f"\nRecord updated successfully!")
            
            # Display records after update
            print("\nRecords after update:")
            display_records(cursor)
        else:
            print("No records were updated.")
            
    except mysql.connector.Error as error:
        print(f"Error updating records: {error}")
        connection.rollback()
    
    finally:
        cursor.close()
        connection.close()
        print("\nDatabase connection closed.")

# Main program
if __name__ == "__main__":
    print("=== MySQL Database - Update Records ===")
    update_records()

OUTPUT

=== MySQL Database - Update Records ===

Records before update:

--- Student Records ---

ID Name Age Grade

----------------------------------------

1 John Smith 18 A

2 Jane Doe 17 B

3 Mike Johnson 19 C

Enter Student ID to update: 2

Current details: ID=2, Name=Jane Doe, Age=17, Grade=B

What do you want to update?

1. Name

2. Age

3. Grade

4. All fields

Enter your choice (1-4): 3

Enter new grade: A

Record updated successfully!

Records after update:

--- Student Records ---

ID Name Age Grade

----------------------------------------

1 John Smith 18 A

2 Jane Doe 17 A

3 Mike Johnson 19 C

Database connection closed.

CONCLUSION

The program successfully demonstrates how to update records in a MySQL database using Python. It shows proper database connection handling, record validation, selective field updates, transaction management, and displays records before and after update for verification.

VIVA QUESTIONS

  1. What is the purpose of the UPDATE statement in SQL?

    The UPDATE statement is used to modify existing records in a table based on specified conditions.

  2. Why should you always use WHERE clause with UPDATE?

    Without WHERE clause, UPDATE will modify all records in the table. WHERE clause specifies which records to update.

  3. How can you update multiple columns in a single UPDATE statement?

    Use comma-separated column=value pairs in the SET clause: SET col1=val1, col2=val2, col3=val3.

  4. What is the difference between UPDATE and INSERT?

    UPDATE modifies existing records, while INSERT adds new records to the table.

  5. How can you verify if the UPDATE operation was successful?

    Check cursor.rowcount to see how many rows were affected, and display records before/after update.