0% found this document useful (0 votes)
14 views24 pages

Python and SQL Programs for Class 12

The document outlines a report file for a 12th-grade class, detailing requirements for Python programs, SQL queries, and Python-SQL connectivity projects. It includes specific programming tasks such as reading and processing text files, creating binary files, implementing data structures, and performing operations with CSV files. Each task is accompanied by an aim, logic, and example Python code, with instructions to execute the code and document the output.

Uploaded by

Mimk Legend
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views24 pages

Python and SQL Programs for Class 12

The document outlines a report file for a 12th-grade class, detailing requirements for Python programs, SQL queries, and Python-SQL connectivity projects. It includes specific programming tasks such as reading and processing text files, creating binary files, implementing data structures, and performing operations with CSV files. Each task is accompanied by an aim, logic, and example Python code, with instructions to execute the code and document the output.

Uploaded by

Mimk Legend
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Report File/Journal Sample [ Class : 12th ]

1) Minimum 15 Python programs


2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

1. Read a Text File Line by Line and Display Each Word Separated by a #:

Aim : To read a text file line by line and display each word separated by a #.

Logic:
1) Open the file in read mode.
2) Read each line.
3) Split each line into words.
4) Display each word separated by a #.

Python Code:

# Open the file in read mode


with open('[Link]', 'r') as file:
# Read each line
for line in file:
# Split each line into words
words = [Link]()
# Display each word separated by a #
print("#".join(words))

Output :
(Execute the above code and write down the output.)

2. Read a Text File and Display the Number of Vowels/Consonants/Uppercase/Lowercase Characters:

Aim:
To read a text file and display the number of vowels, consonants, uppercase, and lowercase characters.

Logic:
1) Open the file in read mode.
2) Read the content of the file.
3) Count vowels, consonants, uppercase, and lowercase characters.

Python Code:

# Open the file in read mode


with open('[Link]', 'r') as file:

Vijay Sir – PGT C.S. Page No : 1


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

# Read the content of the file


content = [Link]()

# Count vowels, consonants, uppercase, and lowercase characters


vowels = sum(1 for char in content if [Link]() in 'aeiou')
consonants = sum(1 for char in content if [Link]() and [Link]() not in 'aeiou')
uppercase = sum(1 for char in content if [Link]())
lowercase = sum(1 for char in content if [Link]())

# Display the counts


print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Uppercase: {uppercase}")
print(f"Lowercase: {lowercase}")

Output :
(Execute the above code and write down the output.)

3. Remove all lines Containing 'a' in a File and Write to another File.

Aim:
To remove all lines containing the character 'a' in a file and write the remaining lines to another file.

Logic:
Open the source file in read mode.
Open the destination file in write mode.
Read each line from the source file.
If the line does not contain the character 'a', write it to the destination file.

Python Code:

source_file = '[Link]'
destination_file = '[Link]'

# Open the source file in read mode


with open(source_file, 'r') as source:
# Open the destination file in write mode
with open(destination_file, 'w') as destination:

Vijay Sir – PGT C.S. Page No : 2


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

# Read each line from the source file


for line in source:
# If the line does not contain the character 'a', write it to the destination file
if 'a' not in [Link]():
[Link](line)

Output :
(Execute the above code and write down the output.)

4. Create a Binary File with Name and Roll Number. Search for a Given Roll Number.

Aim:
To create a binary file with name and roll number, then search for a given roll number and display the name.

Logic:
1) Define a structure for the binary file (e.g., using struct module).
2) Write records (name, roll number) to the binary file.
3) Search for a given roll number and display the associated name.

Python Code:

import struct

# Define the structure for the binary file


record_format = '30si'

# Function to create a binary file


def create_binary_file(filename):
with open(filename, 'wb') as file:
# Write records (name, roll number) to the binary file
[Link]([Link](record_format, 'Alice'.encode('utf-8'), 101))
[Link]([Link](record_format, 'Bob'.encode('utf-8'), 102))
[Link]([Link](record_format, 'Charlie'.encode('utf-8'), 103))

# Function to search for a roll number and display the name


def search_by_roll_number(filename, target_roll_number):
with open(filename, 'rb') as file:
while True:
data = [Link]([Link](record_format))

Vijay Sir – PGT C.S. Page No : 3


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

if not data:
break
name, roll_number = [Link](record_format, data)
if roll_number == target_roll_number:
print(f"Name for Roll Number {target_roll_number}: {[Link]('utf-8')}")
return
print(f"Roll Number {target_roll_number} not found.")

# Create a binary file


binary_filename = '[Link]'
create_binary_file(binary_filename)

# Search for a given roll number


search_roll_number = 102
search_by_roll_number(binary_filename, search_roll_number)

Output :
(Execute the above code and write down the output.)

5. Create a Binary File with Roll Number, Name, and Marks. Input a Roll Number and Update
the Marks.

Aim:
To create a binary file with roll number, name, and marks. Input a roll number and update the marks.

Logic:
1) Define a structure for the binary file.
2) Write records (roll number, name, marks) to the binary file.
3) Input a roll number and update the associated marks.

Python Code:

import struct

# Define the structure for the binary file


record_format = 'i30sf'

# Function to create a binary file


def create_binary_file(filename):

Vijay Sir – PGT C.S. Page No : 4


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

with open(filename, 'wb') as file:


# Write records (roll number, name, marks) to the binary file
[Link]([Link](record_format, 101, 'Alice'.encode('utf-8'), 95.5))
[Link]([Link](record_format, 102, 'Bob'.encode('utf-8'), 90.5))
[Link]([Link](record_format, 103, 'Charlie'.encode('utf-8'), 88.0))

# Function to input a roll number and update the marks


def update_marks_by_roll_number(filename, target_roll_number, new_marks):
with open(filename, 'rb+') as file:
while True:
data = [Link]([Link](record_format))
if not data:
break
roll_number, name, marks = [Link](record_format, data)
if roll_number == target_roll_number:
# Update the marks and write back to the file
[Link](-[Link](record_format), 1)
[Link]([Link](record_format, roll_number, name, new_marks))
print(f"Marks for Roll Number {target_roll_number} updated to {new_marks}.")
return
print(f"Roll Number {target_roll_number} not found.")

# Create a binary file


binary_filename_marks = 'student_marks.bin'
create_binary_file(binary_filename_marks)

# Input a roll number and update the marks


update_roll_number = 102
new_marks_value = 92.0
update_marks_by_roll_number(binary_filename_marks, update_roll_number, new_marks_value)

Output :
(Execute the above code and write down the output.)

6. Write a Random Number Generator that generates random numbers between 1 and 6
(Simulates a Dice).

Aim:
To create a Python program that simulates a dice by generating random numbers between 1 and 6.

Vijay Sir – PGT C.S. Page No : 5


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

Logic:
1) Import the random module.
2) Use [Link]() to generate a random number between 1 and 6.

Python Code:

import random

# Simulate rolling a dice


random_number = [Link](1, 6)

# Display the result


print(f"The dice rolled: {random_number}")

Output :
(Execute the above code and write down the output.)

7. Write a Python Program to Implement a Stack Using List.

Aim:
To implement a stack data structure using a Python list.

Logic:
1) Use a Python list to represent the stack.
2) Implement push() to add elements to the top of the stack.
3) Implement pop() to remove elements from the top of the stack.
4) Implement is_empty() to check if the stack is empty.

Python Code:

class Stack:
def __init__(self):
[Link] = []

def is_empty(self):
return len([Link]) == 0

def push(self, item):


[Link](item)

Vijay Sir – PGT C.S. Page No : 6


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

def pop(self):
if not self.is_empty():
return [Link]()
else:
print("Stack is empty. Cannot pop.")

# Example usage
stack = Stack()
[Link](1)
[Link](2)
[Link](3)

while not stack.is_empty():


popped_item = [Link]()
print(f"Popped item: {popped_item}")

Output :
(Execute the above code and write down the output.)

8. Create a CSV File by Entering User-ID and Password, Read & Search the Password for a Given
User-ID.

Aim:
To create a CSV file by entering user-ID and password, then read and search the password for a given user-ID.

Logic:
1) Use the csv module to handle CSV operations.
2) Implement functions to write user-ID and password to the CSV file.
3) Implement a function to read and search for the password for a given user-ID.

Python Code:

import csv

# Function to create a CSV file with user-ID and password


def create_csv_file(filename):
with open(filename, 'w', newline='') as file:
writer = [Link](file)

Vijay Sir – PGT C.S. Page No : 7


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

[Link](['User-ID', 'Password'])
while True:
user_id = input("Enter User-ID (or 'q' to stop): ")
if user_id.lower() == 'q':
break
password = input("Enter Password: ")
[Link]([user_id, password])

# Function to read and search for the password for a given user-ID
def search_password(filename, target_user_id):
with open(filename, 'r') as file:
reader = [Link](file)
next(reader) # Skip the header row
for row in reader:
if row[0] == target_user_id:
print(f"Password for User-ID '{target_user_id}': {row[1]}")
return
print(f"User-ID '{target_user_id}' not found.")

# Example usage
csv_filename = 'user_passwords.csv'
create_csv_file(csv_filename)

search_user_id = input("Enter User-ID to search: ")


search_password(csv_filename, search_user_id)

Output :
(Execute the above code and write down the output.)

9. Write a Python program to find the intersection of two lists.

Aim: Find the intersection of two lists

Logic:
1. Define two lists.
2. Use list comprehension to find the common elements between the two lists.
3. Print the result.

Vijay Sir – PGT C.S. Page No : 8


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

Python Code:

# Define two lists


list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

# Find the intersection using list comprehension


intersection = [value for value in list1 if value in list2]

# Print the result


print("Intersection of the two lists:", intersection)

Output :
(Execute the above code and write down the output.)

10. Write a Python program to check if a number is Armstrong.

Aim: Check if a number is Armstrong

Logic:
1) Take input for a number.
2) Calculate the sum of the nth power of each digit.
3) Check if the sum is equal to the original number.
4) Print whether the number is Armstrong or not.

Python Code:

# Take input for a number


num = int(input("Enter a number: "))

# Calculate the number of digits in the number


num_digits = len(str(num))

# Initialize a variable to store the sum of nth power of each digit


sum_armstrong = 0
temp_num = num

# Calculate the sum of nth power of each digit


while temp_num > 0:

Vijay Sir – PGT C.S. Page No : 9


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

digit = temp_num % 10
sum_armstrong += digit**num_digits
temp_num //= 10

# Check if the number is Armstrong


is_armstrong = sum_armstrong == num

# Print the result


if is_armstrong:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")

Output :
(Execute the above code and write down the output.)

11. Write a Python program to find the area of a circle.

Aim: Find the area of a circle

Logic:
1) Take input for the radius of the circle.
2) Use the formula area = π * r^2 to calculate the area.
3) Print the result.

Python Code:

import math

# Take input for the radius of the circle


radius = float(input("Enter the radius of the circle: "))

# Calculate the area of the circle


area = [Link] * radius**2

# Print the result


print("Area of the circle:", area)

Output :
(Execute the above code and write down the output.)

Vijay Sir – PGT C.S. Page No : 10


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

12. Write a Python program to find the sum of digits in a number.

Aim: Find the sum of digits in a number

Logic:
1) Take input for a number.
2) Use a loop to extract each digit and add it to the sum.
3) Print the sum of digits.

Python Code:

# Take input for a number


num = int(input("Enter a number: "))

# Initialize a variable to store the sum of digits


sum_of_digits = 0

# Use a loop to extract each digit and add it to the sum


while num > 0:
digit = num % 10
sum_of_digits += digit
num //= 10

# Print the result


print("Sum of digits:", sum_of_digits)

Output :
(Execute the above code and write down the output.)

13. Write a Python program to remove duplicates from a list.

Aim: Remove duplicates from a list

Logic:
1) Define a list with duplicate elements.
2) Use a set to remove duplicates.
3) Print the list without duplicates.

Vijay Sir – PGT C.S. Page No : 11


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

Python Code:

# Define a list with duplicate elements


numbers = [1, 2, 2, 3, 4, 4, 5]

# Remove duplicates using set


unique_numbers = list(set(numbers))

# Print the result


print("List without duplicates:", unique_numbers)

Output :
(Execute the above code and write down the output.)

14. Write a Python program to find the factorial of a number using recursion.

Aim: Find the factorial of a number using recursion

Logic:
1) Define a recursive function to calculate the factorial.
2) Take input for a number.
3) Call the recursive function to find the factorial.
4) Print the result.

Python Code:

# Define a recursive function for factorial


def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

# Take input for a number


num = int(input("Enter a number: "))

# Call the recursive function to find the factorial


result = factorial(num)

Vijay Sir – PGT C.S. Page No : 12


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

# Print the result


print(f"The factorial of {num} is {result}.")

Output :
(Execute the above code and write down the output.)

15. Write a Python program to check if a string is a palindrome.

Aim: Check if a string is a palindrome

Logic:
1) Take input for a string.
2) Compare the string with its reverse.
3) Print whether the string is a palindrome or not.

Python Code:

# Take input for a string


input_string = input("Enter a string: ")

# Check if the string is a palindrome


is_palindrome = input_string == input_string[::-1]

# Print the result


if is_palindrome:
print(f"{input_string} is a palindrome.")
else:
print(f"{input_string} is not a palindrome.")

Output :
(Execute the above code and write down the output.)

Vijay Sir – PGT C.S. Page No : 13


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

SQL Queries

1. Write an SQL query to create a table named students in a relational database to store information
about students, including their unique ID, name, age, and grade, ensuring that each student ID is
unique.

Aim:
To create a table named students with columns student_id, student_name, student_age, and student_grade.

Logic:
1) Use the SQL CREATE TABLE statement to define a new table.
2) Specify the columns, their data types, and any constraints (such as primary key).

SQL Code:

CREATE TABLE students (


student_id INT PRIMARY KEY,
student_name VARCHAR(255),
student_age INT,
student_grade CHAR(1)
);

2. Write an SQL query to insert multiple records into a table named students in a relational database,
providing values for the columns student_id, student_name, student_age, and student_grade for
each record.

Aim:
To insert multiple records into the students table, providing values for the columns student_id, student_name,
student_age, and student_grade for each record.

Logic:
Use the SQL INSERT INTO statement to add records to the students table. Each set of values in the VALUES
clause represents a separate record to be inserted.

SQL Code:

INSERT INTO students (student_id, student_name, student_age, student_grade)


VALUES (1, 'Alice', 18, 'A'),

Vijay Sir – PGT C.S. Page No : 14


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

(2, 'Bob', 19, 'B'),


(3, 'Charlie', 17, 'A');

3. Write an SQL query to update the student_age for a specific record in the students table, setting it
to 20, where the student_name is 'Bob'.

Aim:
To update the student_age for a specific student in the students table.

Logic:
Use the SQL UPDATE statement to modify existing records based on a specified condition. In this case, it
updates the student_age to 20 for the student whose student_name is 'Bob'.

SQL Code:

UPDATE students
SET student_age = 20
WHERE student_name = 'Bob';

4. Write an SQL query to retrieve all columns and records from the students table in a relational
database.

Aim:
To retrieve all columns and records from the students table in a relational database.

Logic:
Use the SQL SELECT statement with the wildcard * to retrieve all columns and records from the specified
table, in this case, students.

SQL Code:

SELECT * FROM students;

Vijay Sir – PGT C.S. Page No : 15


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

5. Write an SQL query to retrieve the columns student_name and student_grade from the students table
for records where the student_age is greater than 18.

Aim:
To retrieve the columns student_name and student_grade from the students table for records where the
student_age is greater than 18.

Logic:
Use the SQL SELECT statement to specify the columns to be retrieved (student_name and student_grade). The
WHERE clause filters the records, including only those where the student_age is greater than 18.

SQL Code:

SELECT student_name, student_grade


FROM students
WHERE student_age > 18;

6. Write an SQL query to delete a record from the students table where the student_name is 'Charlie'.

Aim:
To delete a record from the students table where the value in the student_name column is 'Charlie'.

Logic:
Use the SQL DELETE FROM statement to remove a record from the specified table (students) based on a
specified condition. In this case, it deletes the record where the student_name is 'Charlie'.

SQL Code:

DELETE FROM students


WHERE student_name = 'Charlie';

7. Write an SQL query to create tables named courses and enrollments in a relational database, insert
records into these tables, and then retrieve information about students and their enrolled courses.

Aim:
To create tables named courses and enrollments in a relational database, insert records into these tables, and
then retrieve information about students and their enrolled courses using a query.

Vijay Sir – PGT C.S. Page No : 16


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

Logic:
1) Use the SQL CREATE TABLE statement to create a table named courses with columns course_id
and course_name.
2) Insert records into the courses table using the SQL INSERT INTO statement.
3) Create a table named enrollments with columns enrollment_id, student_id, and course_id.
Also, define foreign key constraints to reference the students and courses tables.
4) Insert records into the enrollments table using the SQL INSERT INTO statement.
5) Use a SQL SELECT statement with JOIN clauses to retrieve information about students and their
enrolled courses by joining the students, enrollments, and courses tables.

SQL Code:

-- Create a table for courses


CREATE TABLE courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(255)
);

-- Insert records into the courses table


INSERT INTO courses (course_id, course_name)
VALUES (1, 'Math'), (2, 'English');

-- Create a table for enrollments


CREATE TABLE enrollments (
enrollment_id INT PRIMARY KEY,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

-- Insert records into the enrollments table


INSERT INTO enrollments (enrollment_id, student_id, course_id)
VALUES (101, 1, 1),
(102, 1, 2),
(103, 2, 1);

-- Query to get students and their enrolled courses


SELECT students.student_name, courses.course_name
FROM students

Vijay Sir – PGT C.S. Page No : 17


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

JOIN enrollments ON students.student_id = enrollments.student_id


JOIN courses ON enrollments.course_id = courses.course_id;

Programs based on Python - SQL connectivity

Question 1

Aim:
To integrate SQL with Python using the MySQL module, create a table named students and insert data into it.

Logic:
1) Use the [Link] module to establish a connection to the MySQL server.
2) Create a cursor object to interact with the database.
3) Execute a SQL CREATE TABLE statement to create a table named students with columns such as
rollno, name, age, and percentage.
4) Execute a SQL INSERT INTO statement to insert data into the students table.
5) Commit the changes to the database.

Code:

import [Link]

# Replace these values with your MySQL server details


host = "your_mysql_host"
user = "your_mysql_user"
password = "your_mysql_password"
database = "your_mysql_database"

# Establish a connection to the MySQL server


connection = [Link](
host=host,
user=user,
password=password,
database=database
)

# Create a cursor object to interact with the database


cursor = [Link]()

# Execute a SQL CREATE TABLE statement to create the students table

Vijay Sir – PGT C.S. Page No : 18


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

create_table_query = """
CREATE TABLE IF NOT EXISTS students (
rollno INT PRIMARY KEY,
name VARCHAR(255),
age INT,
percentage FLOAT
)
"""
[Link](create_table_query)

# Insert data into the students table


insert_query = "INSERT INTO students (rollno, name, age, percentage) VALUES (%s, %s, %s, %s)"
data_to_insert = [
(101, 'Alice', 20, 85.5),
(102, 'Bob', 22, 78.0),
(103, 'Charlie', 21, 92.3),
(104, 'David', 23, 75.8),
(105, 'Eva', 20, 89.2)
]
[Link](insert_query, data_to_insert)

# Commit the changes to the database


[Link]()

# Clean up resources
[Link]()
[Link]()

Question 2

Aim:
To integrate SQL with Python using the MySQL module, fetch the data of students from the students table, and
display it.

Logic:
1) Use the [Link] module to establish a connection to the MySQL server.
2) Create a cursor object to interact with the database.
3) Execute a SQL SELECT query to fetch data from the students table.
4) Display the fetched data.

Vijay Sir – PGT C.S. Page No : 19


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

Code:

import [Link]

# Replace these values with your MySQL server details


host = "your_mysql_host"
user = "your_mysql_user"
password = "your_mysql_password"
database = "your_mysql_database"

# Establish a connection to the MySQL server


connection = [Link](
host=host,
user=user,
password=password,
database=database
)

# Create a cursor object to interact with the database


cursor = [Link]()

# Fetch data from the students table


select_query = "SELECT * FROM students"
[Link](select_query)
result = [Link]()

# Display the fetched data


print("Student Data:")
for row in result:
print(row)

# Clean up resources
[Link]()
[Link]()

Question 3

Aim:
To integrate SQL with Python using the MySQL module, search for a student using their roll_no in the students
table. If the student is present, display the record; otherwise, show a "not found" message. Ask for another
student and repeat the process.

Vijay Sir – PGT C.S. Page No : 20


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

Logic:
1) Use the [Link] module to establish a connection to the MySQL server.
2) Create a cursor object to interact with the database.
3) Take input for the student's roll_no.
4) Execute a SQL SELECT query with a WHERE clause to search for the student in the students table.
5) If the student is found, display the record; otherwise, show a "not found" message.
6) Ask for another student and repeat the process.

Code:

import [Link]

# Replace these values with your MySQL server details


host = "your_mysql_host"
user = "your_mysql_user"
password = "your_mysql_password"
database = "your_mysql_database"

# Establish a connection to the MySQL server


connection = [Link](
host=host,
user=user,
password=password,
database=database
)

# Create a cursor object to interact with the database


cursor = [Link]()

while True:
# Take input for student's roll_no
roll_no = int(input("Enter student's roll_no (0 to exit): "))

if roll_no == 0:
break # Exit the loop if roll_no is 0

# Execute a SQL SELECT query to search for the student


select_query = "SELECT * FROM students WHERE rollno = %s"
[Link](select_query, (roll_no,))
result = [Link]()

# Display the result

Vijay Sir – PGT C.S. Page No : 21


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

if result:
print("Student Found:")
print(result)
else:
print("Student not found.")

# Clean up resources
[Link]()
[Link]()

Question 4

Aim:
To integrate SQL with Python using the MySQL module, search for a student using their roll_no in the students
table. If the student is found, ask the user what information they want to update, and then update the record. If
not found, ask for another student.

Logic:
1) Use the [Link] module to establish a connection to the MySQL server.
2) Create a cursor object to interact with the database.
3) Take input for the student's roll_no.
4) Execute a SQL SELECT query with a WHERE clause to search for the student in the students table.
5) If the student is found, ask the user what information they want to update (age or percentage) and take
input for the updated information.
6) Execute a SQL UPDATE query to update the selected information in the record.
7) If the student is not found, show a message and ask for another student.

Code:

import [Link]

# Replace these values with your MySQL server details


host = "your_mysql_host"
user = "your_mysql_user"
password = "your_mysql_password"
database = "your_mysql_database"

# Establish a connection to the MySQL server


connection = [Link](
host=host,

Vijay Sir – PGT C.S. Page No : 22


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

user=user,
password=password,
database=database
)

# Create a cursor object to interact with the database


cursor = [Link]()

while True:
# Take input for student's roll_no
roll_no = int(input("Enter student's roll_no (0 to exit): "))

if roll_no == 0:
break # Exit the loop if roll_no is 0

# Execute a SQL SELECT query to search for the student


select_query = "SELECT * FROM students WHERE rollno = %s"
[Link](select_query, (roll_no,))
result = [Link]()

# If the student is found, ask the user what to update


if result:
print("Student Found:")
print(result)

# Ask the user what information to update


update_choice = input("What do you want to update? (age/percentage): ").lower()

# Take input for updated information based on user's choice


if update_choice == 'age':
new_age = int(input("Enter updated age: "))
update_query = "UPDATE students SET age = %s WHERE rollno = %s"
[Link](update_query, (new_age, roll_no))
[Link]()
print("Age updated successfully.")
elif update_choice == 'percentage':
new_percentage = float(input("Enter updated percentage: "))
update_query = "UPDATE students SET percentage = %s WHERE rollno = %s"
[Link](update_query, (new_percentage, roll_no))
[Link]()
print("Percentage updated successfully.")
else:
print("Invalid choice. Please enter 'age' or 'percentage'.")

Vijay Sir – PGT C.S. Page No : 23


Report File/Journal Sample [ Class : 12th ]
1) Minimum 15 Python programs
2) SQL Queries – Minimum 5 sets using one table / two tables
3) Minimum 4 programs based on Python - SQL connectivity

else:
print("Student not found. Please try again.")

# Clean up resources
[Link]()
[Link]()

Vijay Sir – PGT C.S. Page No : 24

You might also like