Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
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
- Start
- Import mysql.connector module
- Establish connection to MySQL database
- Create cursor object
- Display all records before update
- Accept record ID to update from user
- Accept new values for fields to update
- Execute UPDATE query with WHERE clause
- Commit the transaction
- Display confirmation message
- Display updated records
- Close cursor and connection
- 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
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.
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.
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.
What is the difference between UPDATE and INSERT?
UPDATE modifies existing records, while INSERT adds new records to the table.
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.