CS Practical
CS Practical
NO SIGN
1 Compute Fibonacci Series
2 Calculate Factorial
3 Palindrome Check
4 Prime Number Generator
5 Sin (x, n) Approximation
6 Insertion Sort
7 Remove Duplicate Values
8 Sum of List Elements
9 User Module Import
10 File Reader with Separator
11 Count Vowels, Consonants, and Case
12 Remove Lines with Character 'a'
13 Create Binary File
14 Binary File Search by Roll Number
15 Update Marks by Roll Number
16 Random Number Generation
17 Stack Implementation
18 CSV File Operations
Data Definition Language (DDL) in
19
SQL
Data Manipulation Language (DML)
20
in SQL
21 Clauses in SQL
22 Basic SQL Operations with Equi-Join
23 Aggregate Functions in SQL
Display All Records with MySQL
24
using Python
Fetch First 3 Records in MySQL
25
using Python
Delete a Record in MySQL using
26
Python
Insert New Record in MySQL using
27
Python
EXP NO :1
DATE :
AIM:
To compute the Fibonacci series for a given number of terms using a user-defined
function in Python.
ALGORITHM:
SOURCE CODE:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" , ")
a, b = b, a + b
# Input: number of terms
num_terms = int(input("Enter the number of terms: "))
fibonacci(num_terms)
OUTPUT:
Enter the number of terms: 11
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ,
RESULT:
EXP NO :2
DATE :
CALCULATE FACTORIAL
AIM:
To calculate the factorial of given ‘n’ numbers using a user-defined function in Python.
ALGORITHM:
SOURCE CODE:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
n = int(input("Enter a number to compute factorial: "))
print(factorial(n))
OUTPUT:
Enter a number to compute factorial: 8
40320
RESULT:
EXP NO :3
DATE :
PALINDROME CHECK
AIM:
To check if the entered string is a palindrome or not in Python.
ALGORITHM:
SOURCE CODE:
def is_palindrome(s):
return s == s[::-1]
s = input("Enter a string: ")
print("Palindrome:", s[::-1])
print(is_palindrome(s))
if is_palindrome(s):
print(f'{s[::-1]} is a Palindrome of {s}')
else:
print(f'{s[::-1]} is not a Palindrome of {s}')
OUTPUT:
Enter a string: malayalam
Palindrome: malayalam
True
malayalam is a Palindrome of malayalam
RESULT:
EXP NO :4
DATE :
AIM:
To compute prime numbers between 2 to n in Python.
ALGORITHM:
SOURCE CODE:
def prime():
start = 2
end = int(input("Enter the end range number: "))
for i in range(start, end+1):
is_prime = True
for j in range(2, int(i**0.5) + 1):
if i % j == 0:
is_prime = False
break
if is_prime and i > 1:
print(i)
prime()
OUTPUT:
Enter the end range number: 15
2
3
5
7
11
13
RESULT:
EXP NO :5
DATE :
SIN(X, N) APPROXIMATION
AIM:
To compute the sin(x, n) function using a mathematical approximation in Python.
ALGORITHM:
SOURCE CODE:
import math
def sin(x, n):
s=0
for i in range(n):
sign = (-1) ** i
pi = 22 / 7
y = x * (pi / 180) # Change from 80 to 180 to convert degrees to radians
s += (y ** (2 * i + 1)) / math.factorial(2 * i + 1) * sign
return s
x = int(input("Enter the value of x (degree): "))
n = int(input("Enter the value of n: "))
print(round(sin(x, n), 2))
OUTPUT:
Enter the value of x (degree): 28
Enter the value of n: 3
0.47
RESULT:
EXP NO :6
DATE :
LIST SORTING
AIM:
To perform insertion sorting in a list in Python.
ALGORITHM:
SOURCE CODE:
lst = [10, 5, 18, 12, 4, 6]
print("Original list:", lst)
for i in range(1, len(lst)):
key = lst[i]
j=i-1
while j >= 0 and key < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
print("List after insertion sort:", lst)
OUTPUT:
Original list: [10, 5, 6, 12, 4, 18]
List after insertion sort: [4, 5, 6, 10, 12, 18]
RESULT:
EXP NO :7
DATE :
AIM:
To remove duplicate values in list in Python.
ALGORITHM:
SOURCE CODE:
a = eval(input("Enter list: "))
n = []
for i in a:
if i not in n:
n.append(i)
print(n)
OUTPUT:
Enter list: [4,5,6,7,8,4,5,3,2]
[4, 5, 6, 7, 8, 3, 2]
RESULT:
EXP NO :8
DATE :
AIM:
To compute the sum of all numbers in a list in Python.
ALGORITHM:
SOURCE CODE:
def findSum(lst, num):
if num == 0:
return 0
else:
return lst[num - 1] + findSum(lst, num - 1)
mylist = []
num = int(input("Enter how many numbers: "))
for i in range(num):
n = int(input("Enter Element " + str(i + 1) + ": "))
mylist.append(n)
sum = findSum(mylist, len(mylist))
print("Sum of List items ", mylist, " is: ", sum)
OUTPUT:
Enter how many numbers: 7
Enter Element 1: 6
Enter Element 2: 5
Enter Element 3: 3
Enter Element 4: 8
Enter Element 5: 9
Enter Element 6: 66
Enter Element 7: 9
Sum of List items [6, 5, 3, 8, 9, 66, 9] is: 106
RESULT:
EXP NO :9
DATE :
AIM:
To import a user-defined module into a Python program.
ALGORITHM:
SOURCE CODE:
sqrec.py
def square():
num = int(input("Enter size square in cm: "))
area = num * num
print("Area of square: ", area, " sqcm")
return area
def rect():
length = int(input("Enter length of rectangle in cm: "))
breadth = int(input("Enter breadth of rectangle in cm: "))
area = length * breadth
print("Area of rectangle: ", area, " sqcm")
return area
usermodule.py
from sqrect import square, rect
# Call the functions from the imported user module
square()
rect()
OUTPUT:
Enter size square in cm: 5
Area of square: 25 sqcm
Enter length of rectangle in cm: 9
Enter breadth of rectangle in cm: 3
Area of rectangle: 27 sqcm
RESULT:
EXP NO : 10
DATE :
AIM:
To read a text file line by line and display each word separated by a ‘#’ in Python.
ALGORITHM:
SOURCE CODE:
def read_file(filename):
try:
rfile = open(filename, 'r')
for line in rfile:
words = line.split()
print('#'.join(words))
file.close()
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
read_file("readme.txt")
readme.txt
Fun Fact 1
There's a poem called the Zen of Python that can be read by writing import this in the Interpreter.
Fun Fact 2
Python was released in 1991, while Java was released in 1995, making Python older than Java.
OUTPUT:
Fun#Fact#1
There's#a#poem#called#the#Zen#of#Python#that#can#be#read#by#writing#import#this#in#the#
Interpreter.
Fun#Fact#2
Python#was#released#in#1991,#while#Java#was#released#in#1995,#making#Python#older#tha
n#Java.
RESULT:
EXP NO : 11
DATE :
AIM:
To read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file using Python.
ALGORITHM:
SOURCE CODE:
file = open("readme.txt", "r")
content = file.read()
vowels = 0
consonants = 0
lowercase = 0
uppercase = 0
nums=0
for ch in content:
if ch.islower():
lowercase += 1
elif ch.isupper():
uppercase += 1
ch = ch.lower()
if ch in ['a', 'e', 'i', 'o', 'u']:
vowels += 1
elif ch in ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']:
consonants += 1
if ch.isdigit():
nums+=1
file.close()
print("Total No of Character: ",len(content.replace(" ", "")))
print("No of Vowels are: ", vowels)
print("No of Consonants are: ", consonants)
print("No of Lowercase letters: ", lowercase)
print("No of Uppercase letters: ", uppercase)
print("No of Numbers: ", nums)
readme.txt
Fun Fact 1
There's a poem called the Zen of Python that can be read by writing import this in the Interpreter.
Fun Fact 2
Python was released in 1991, while Java was released in 1995, making Python older than Java.
OUTPUT:
Total No of Character: 178
No of Vowels are: 56
No of Consonants are: 103
No of Lowercase letters: 147
No of Uppercase letters: 12
No of Numbers: 10
RESULT:
EXP NO : 12
DATE :
AIM:
To remove all lines containing the character 'a' in a text file and write the result to another
file in Python.
ALGORITHM:
SOURCE CODE:
def rewrite(input_file, output_file):
try:
infile = open(input_file, 'r')
outfile = open(output_file, 'w')
for line in infile:
if 'a' not in line and 'A' not in line:
outfile.write(line)
print(f"Lines without 'a' have been written to '{output_file}'.")
except FileNotFoundError:
print(f"The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
infile.close()
outfile.close()
rewrite("input.txt", "output.txt")
input.txt
A for Apple
B for Ball
C for Cat
One
Two
Three
OUTPUT:
Lines without 'a' have been written to 'output.txt'.
output.txt
One
Two
Three
RESULT:
EXP NO : 13
DATE :
AIM:
To create a binary file with roll number, name, and marks in Python using list and
dictionary.
ALGORITHM:
SOURCE CODE:
import pickle
students_list = [ [101, "Ari Kumar", 85] , [102, "Muthal Raj", 90] , [103, "Shaik", 78] ]
with open("students_list.bin", "wb+") as file:
pickle.dump(students_list, file)
file.seek(0)
data=pickle.load(file)
print("Data written to students_list.bin as a list. ", data)
students_dict = {
101: {"name": "Ari Kumar", "marks": 85},
102: {"name": "Muthal Raj", "marks": 90},
103: {"name": "Shaik", "marks": 78}
}
with open("students_dict.bin", "wb+") as file:
pickle.dump(students_dict, file)
file.seek(0)
data=pickle.load(file)
print("\nData written to students_dict.bin as a dictionary. ", data)
OUTPUT:
Data written to students_list.bin as a list. [[101, 'Ari Kumar', 85], [102, 'Muthal Raj', 90], [103,
'Shaik', 78]]
Data written to students_dict.bin as a dictionary. {101: {'name': 'Ari Kumar', 'marks': 85}, 102:
{'name': 'Muthal Raj', 'marks': 90}, 103: {'name': 'Shaik', 'marks': 78}}
RESULT:
EXP NO : 14
DATE :
AIM:
To search for a given roll number in a binary file and display the corresponding name and
mark, if not found display appropriate message.
ALGORITHM:
SOURCE CODE:
import pickle
def search_student(filename, roll_number):
try:
file = open(filename, "rb")
students_dict = pickle.load(file)
if roll_number in students_dict:
student = students_dict[roll_number]
print(f"Roll Number: {roll_number}")
print(f"Name: {student['name']}")
print(f"Marks: {student['marks']}")
else:
print(f"Roll number {roll_number} not found.")
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
filename = "students_dict.bin"
roll_number = int(input("Enter roll number to search: "))
search_student(filename, roll_number)
OUTPUT:
Enter roll number to search: 102
Roll Number: 102
Name: Muthal Raj
Marks: 90
RESULT:
EXP NO : 15
DATE :
AIM:
To input a roll number and update the marks in a binary file using Python.
ALGORITHM:
SOURCE CODE:
import pickle
def update_marks(filename, roll_number, new_marks):
try:
file = open(filename, "rb+")
students_dict = pickle.load(file)
if roll_number in students_dict:
students_dict[roll_number]['marks'] = new_marks
print(f"Updated marks for roll number {roll_number} to {new_marks}.")
file.seek(0)
pickle.dump(students_dict, file)
file.truncate()
else:
print(f"Roll number {roll_number} not found in the file.")
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
filename = "students_dict.bin"
roll_number = int(input("Enter roll number to update: "))
new_marks = int(input("Enter new marks: "))
update_marks(filename, roll_number, new_marks)
OUTPUT:
Enter roll number to update: 102
Enter new marks: 99
Updated marks for roll number 102 to 99.
RESULT:
EXP NO : 16
DATE :
AIM:
To write a random number generator that generates random numbers between 1 and
6 (simulates a dice).
ALGORITHM:
SOURCE CODE:
import random
c = 'y'
b=6
while c == 'y':
a = random.randint(1, b)
print(a)
c = input("Roll the dice again (y/n): ")
OUTPUT:
1
Roll the dice again (y/n): y
6
Roll the dice again (y/n): y
2
Roll the dice again (y/n): y
5
Roll the dice again (y/n): n
RESULT:
EXP NO : 17
DATE :
STACK IMPLEMENTATION
AIM:
To write a Python program to implement a stack using list.
ALGORITHM:
SOURCE CODE:
stack = []
def push():
a = int(input("Enter the element to push into stack: "))
stack.append(a)
return a
def pop():
if stack == []:
print("Stack empty… underflow case… cannot delete the element")
else:
print("Deleted element is:", stack.pop())
def display():
if stack == []:
print("Stack empty… no elements")
else:
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
print("STACK OPERATION")
print("***************************************")
choice = "y"
while choice == "y":
print("1. PUSH")
print("2. POP")
print("3. DISPLAY ELEMENTS OF STACK")
print("***************************************")
c = int(input("Enter the choice: "))
if c == 1:
push()
elif c == 2:
pop()
elif c == 3:
display()
else:
print("Wrong input")
choice = input("Do you want to continue (y/n): ")
OUTPUT:
STACK OPERATION
***************************************
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 3
Stack empty… no elements
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 1
Enter the element to push into stack: 30
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 1
Enter the element to push into stack: 25
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 2
Deleted element is: 35
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 3
25
30
RESULT:
EXP NO : 18
DATE :
AIM:
To create a CSV file by entering user-id and password, read and search the password
for given userid in Python.
ALGORITHM:
SOURCE CODE:
import csv
def insert_record():
with open("data.csv", "a", newline='') as file:
writer = csv.writer(file)
writer.writerow(["UserName","Password"])
repeat = int(input("How many IDs do you wish to enter: "))
count = 0
credentials = []
while count < repeat:
uid = input("User Name: ")
pwd = input("Password: ")
credentials.append([uid, pwd])
count += 1
writer.writerows(credentials)
print("Records have been added successfully.")
def search_record(userid):
found = False
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == userid:
print(f'User Name : {row[0]}\nPassword : {row[1]}')
found = True
break
if not found:
print(f"The given User Name '{userid}' not found.")
option = int(input("1. Insert Record\n2. Search Record\nEnter your option: "))
if option == 1:
insert_record()
elif option == 2:
uid = input("Enter the User Name to search: ")
search_record(uid)
else:
print("Invalid Option")
OUTPUT:
1. Insert Record
2. Search Record
Enter your option: 1
How many IDs do you wish to enter: 3
User Name: muthal
Password: raj
User Name: vijay
Password: antony
User Name: harris
Password: jayaraj
Records have been added successfully.
1. Insert Record
2. Search Record
Enter your option: 2
Enter the User Name to search: muthal
User Name : muthal
Password : raj
RESULT:
EXP NO : 19
DATE :
AIM:
To understand and perform operations of Data Definition Language (DDL) in SQL,
including creating a database, creating a table within the database, altering the table structure,
and dropping the table and database.
ALGORITHM:
QUERIES:
CREATE DATABASE School;
SHOW DATABASES;
USE School;
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50), Age
INT, Grade CHAR(1) );
DESCRIBE Students;
ALTER TABLE Students ADD COLUMN Address VARCHAR(100);
ALTER TABLE Students DROP COLUMN Address;
ALTER TABLE Students DROP PRIMARY KEY;
ALTER TABLE Students ADD PRIMARY KEY(StudentID);
DROP TABLE Students;
DROP DATABASE School;
OUTPUT:
Database
auction
information_schema
mysql
performance_schema
phpmyadmin
school
studentdb
test
Field Type Null Key Default Extra
StudentID int(11) NO PRI NULL
Name varchar(50) YES NULL
Age int(11) YES NULL
Grade char(1) YES NULL
RESULT:
EXP NO : 20
DATE :
AIM:
To understand and perform operations of Data Manipulation Language (DML) in SQL,
including inserting, selecting, updating, and deleting data within a database table.
ALGORITHM:
QUERIES:
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50), Age
INT, Grade CHAR(1) );
INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (1, 'Muthal', 17, 'A');
INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (2, 'Raj', 16, 'B');
INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (3, 'Raja', 17, 'A');
SELECT * FROM Students;
SELECT Name, Grade FROM Students;
SELECT * FROM Students WHERE Grade = 'A';
UPDATE Students SET Age = 16 WHERE Name = 'Raja';
DELETE FROM Students WHERE StudentID = 3;
OUTPUT:
SELECT * FROM Students;
StudentID Name Age Grade
1 Muthal 17 A
2 Raj 16 B
3 Raja 17 A
Raj B
Raja A
3 Raja 17 A
After UPDATE Students SET Age = 16 WHERE Name = 'Raja';
StudentID Name Age Grade
1 Muthal 17 A
2 Raj 16 B
3 Raja 16 A
RESULT:
EXP NO : 21
DATE :
CLAUSES IN SQL
AIM:
To understand clauses in SQL like DISTINCT, WHERE, IN, BETWEEN, ORDER BY,
NULL, GROUP BY, and HAVING using SELECT command.
ALGORITHM:
QUERIES:
SELECT DISTINCT Age FROM Students;
SELECT * FROM Students WHERE Age > 18;
SELECT * FROM Students WHERE Age IN (18, 19, 20);
SELECT * FROM Students WHERE Age BETWEEN 18 AND 25;
SELECT * FROM Students ORDER BY Name ASC;
SELECT * FROM Students WHERE Email IS NULL;
SELECT Age, COUNT(*) AS TotalStudents FROM Students GROUP BY Age;
SELECT Age, COUNT(*) AS TotalStudents FROM Students GROUP BY Age HAVING
COUNT(*) > 1;
OUTPUT:
StudentID Name Age Grade Email
1 Muthal 17 A [email protected]
2 Raj 16 B NULL
4 Sri Gopal 20 B NULL
5 Sudha 22 A [email protected]
6 Mathan 19 B NULL
7 Abhinaya 20 C [email protected]
8 Akshara 18 A [email protected]
RESULT:
EXP NO : 22
DATE :
AIM:
To understand and implement equi-joins in SQL, allowing retrieval of related data from
multiple tables based on a common attribute.
ALGORITHM:
QUERIES:
SELECT Students.Name, Enrollments.Course FROM Students JOIN Enrollments ON
Students.StudentID = Enrollments.StudentID;
Table: Students
StudentID Name Age Grade Email
1 Muthal 17 A [email protected]
2 Raj 16 B NULL
3 Sudha 22 A [email protected]
4 Sri Gopal 20 B NULL
5 Akshara 18 A [email protected]
6 Mathan 19 B NULL
7 Abhinaya 20 C [email protected]
Table: Enrollments
EnrollmentID StudentID Course
101 1 Mathematics
102 2 Science
103 1 English
104 3 Computer
105 2 Physics
106 5 Chemistry
107 6 Biology
108 7 Marketing
109 3 Business
110 5 Tamil
OUTPUT:
Name Course
Muthal Mathematics
Raj Science
Muthal English
Sudha Computer
Raj Physics
Akshara Chemistry
Mathan Biology
Abhinaya Marketing
Sudha Business
Akshara Tamil
RESULT:
EXP NO : 23
DATE :
AIM:
To execute aggregate functions (COUNT, SUM, AVG, MAX, MIN) using SELECT
command in SQL.
ALGORITHM:
QUERIES:
SELECT COUNT(*) AS TotalStudents FROM Students;
SELECT AVG(Age) AS AverageAge FROM Students;
SELECT MAX(Age) AS MaxAge FROM Students;
SELECT MIN(Age) AS MinAge FROM Students;
SELECT Sum(Age)/COUNT(Age) AS AverageAge FROM Students;
SELECT Grade, COUNT(*) AS CountPerGrade FROM Students GROUP BY Grade;
OUTPUT:
SELECT COUNT(*) AS TotalStudents FROM Students;
TotalStudents
7
RESULT:
EXP NO : 24
DATE :
AIM:
To interface with a MySQL database and display all records from a table using Python,
by using the mysql.connector library.
ALGORITHM:
SOURCE CODE:
import mysql.connector
def display_records():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "SELECT * FROM students;"
cursor.execute(query)
records = cursor.fetchall()
print("Displaying all records from the students table:")
print(f"StudentID\tName\t\tAge\tGrade\tEmail")
for row in records:
print(f"{row[0]}\t\t{row[1]}\t\t{row[2]}\t{row[3]}\t{row[4]}")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
display_records()
OUTPUT:
Connected to the database.
Displaying all records from the students table:
StudentID Name Age Grade Email
1 Muthal 17 A [email protected]
2 Raj 16 B None
3 Sudha 22 A [email protected]
4 Sri Gopal 20 B None
5 Akshara 18 A [email protected]
6 Mathan 19 B None
7 Abhinaya 20 C [email protected]
Database connection closed.
RESULT:
EXP NO : 25
DATE :
AIM:
To delete a specific record from a table in MySQL using Python, by using the
mysql.connector library.
ALGORITHM:
SOURCE CODE:
import mysql.connector
def delete_record(student_id):
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "DELETE FROM students WHERE StudentID = %s"
cursor.execute(query, (student_id,))
connection.commit()
if cursor.rowcount > 0:
print(f"Record with StudentID {student_id} deleted successfully.")
else:
print(f"No record found with StudentID {student_id}.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
student_id = int(input("Enter the StudentID of the record to delete: "))
delete_record(student_id)
OUTPUT:
Enter the StudentID of the record to delete: 6
Connected to the database.
Record with StudentID 6 deleted successfully.
Database connection closed.
RESULT:
EXP NO : 26
DATE :
AIM:
To fetch the first three records from a table in MySQL using Python, by using the
mysql.connector library.
ALGORITHM:
SOURCE CODE:
import mysql.connector
def fetch_first_three_records():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "SELECT * FROM students LIMIT 3;"
cursor.execute(query)
records = cursor.fetchall()
print("Displaying the first three records from the students table:")
print(f"StudentID\tName\t\tAge\tGrade\tEmail")
for row in records:
print(f"{row[0]}\t\t{row[1]}\t\t{row[2]}\t{row[3]}\t{row[4]}")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
fetch_first_three_records()
OUTPUT:
Connected to the database.
Displaying the first three records from the students table:
StudentID Name Age Grade Email
1 Muthal 17 A [email protected]
2 Raj 16 B None
3 Sudha 22 A [email protected]
Database connection closed.
RESULT:
EXP NO : 27
DATE :
AIM:
To insert a new record into a MySQL table using Python, by using the mysql.connector
library.
ALGORITHM:
SOURCE CODE:
import mysql.connector
def insert_record(student_id, name, age, grade, email):
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "INSERT INTO students (StudentID, Name, Age, Grade, Email) VALUES (%s,
%s, %s, %s, %s)"
values = (student_id, name, age, grade, email)
cursor.execute(query, values)
connection.commit()
print(f"Record inserted successfully with StudentID {student_id}.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
student_id = int(input("Enter StudentID: "))
name = input("Enter Name: ")
age = int(input("Enter Age: "))
grade = input("Enter Grade: ")
email = input("Enter Email (or 'None' if not available): ")
email = None if email.lower() == "none" else email
insert_record(student_id, name, age, grade, email)
OUTPUT:
Enter StudentID: 6
Enter Name: Mathan
Enter Age: 19
Enter Grade: B
Enter Email (or 'None' if not available): None
Connected to the database.
Record inserted successfully with StudentID 6.
Database connection closed.
RESULT: