Use Python to connect and interact with a MySQL database. Write the program to perform the following task
Q.6 Use Python to connect and interact with a MySQL database. Write the program to perform the following task
Solution :-
import mysql.connector # Establish connection to the MySQL database try: connection = mysql.connector.connect( host="localhost", # Replace with your MySQL host user="root", # Replace with your MySQL username password="password", # Replace with your MySQL password database="Student" # Replace with your database name ) if connection.is_connected(): print("Connected to the database successfully!") cursor = connection.cursor() # Display all records from the Students table query = "SELECT * FROM Students" cursor.execute(query) records = cursor.fetchall() print("\nAll Records:") for record in records: print(record) # Insert a new record into the Students table query = "INSERT INTO Students (StudentID, StudentName, Age, Class, Marks) VALUES (%s, %s, %s, %s, %s)" new_student = (6, "Fiona Adams", 16, "11th", 78) cursor.execute(query, new_student) connection.commit() print("\nNew record inserted successfully.") # Display all records after insertion query = "SELECT * FROM Students" cursor.execute(query) records = cursor.fetchall() print("\nAll Records After Insertion:") for record in records: print(record) # Update the marks of the student with StudentID = 5 update_query = "UPDATE Students SET Marks = %s WHERE StudentID = %s" cursor.execute(update_query, (70, 5)) connection.commit() print("\nMarks updated successfully for StudentID = 5.") # Fetch and display the updated record fetch_query = "SELECT * FROM Students WHERE StudentID = %s" cursor.execute(fetch_query, (5,)) updated_record = cursor.fetchone() print("\nUpdated Record:") print(updated_record) except mysql.connector.Error as err: print(f"Error: {err}") finally: if connection.is_connected(): cursor.close() connection.close() print("\nDatabase connection closed.")