0% found this document useful (0 votes)
15 views5 pages

Python SQL Programs for CBSE Grade 12

The document outlines Python programs for various SQL operations on a MySQL database named 'School', specifically focusing on a 'Student' table. It includes tasks such as creating a table, inserting records, updating, deleting, and retrieving data, as well as counting and sorting records based on specific criteria. Each task is associated with a CBSE exam year from 2015 to 2024, providing example code for implementation.

Uploaded by

jayaram.1960k
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)
15 views5 pages

Python SQL Programs for CBSE Grade 12

The document outlines Python programs for various SQL operations on a MySQL database named 'School', specifically focusing on a 'Student' table. It includes tasks such as creating a table, inserting records, updating, deleting, and retrieving data, as well as counting and sorting records based on specific criteria. Each task is associated with a CBSE exam year from 2015 to 2024, providing example code for implementation.

Uploaded by

jayaram.1960k
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

Python–SQL Interface Programs (Grade 12 – Last 10 Years CBSE Programs)

Q1. [CBSE 2015] Create a table using Python


Write a Python program to connect with the MySQL database `School` and create a table
`Student` with fields: RollNo (int), Name (varchar(30)), Marks (int).

Answer:

import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

[Link]("CREATE TABLE Student (RollNo INT, Name VARCHAR(30), Marks INT)")

[Link]()
print("Table Student created successfully")

[Link]()

Q2. [CBSE 2016] Insert a record into Student


Write a Python program to insert one record (101, 'Amit', 89) into the Student table.

Answer:
import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

sql = "INSERT INTO Student VALUES (%s, %s, %s)"


data = (101, "Amit", 89)
[Link](sql, data)

[Link]()
print("Record inserted successfully")

[Link]()

Q3. [CBSE 2017] Insert multiple records into Student


Write a Python program to insert three records into the Student table using executemany().
Answer:
import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

sql = "INSERT INTO Student VALUES (%s, %s, %s)"


data = [(102, "Neha", 78), (103, "Ravi", 92), (104, "Farida", 85)]

[Link](sql, data)
[Link]()

print([Link], "records inserted successfully")


[Link]()

Q4. [CBSE 2018] Display all records from Student


Write a Python program to fetch and display all records from the Student table.

Answer:
import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

[Link]("SELECT * FROM Student")


rows = [Link]()

for row in rows:


print(row)

[Link]()

Q5. [CBSE 2019] Search a student record


Write a Python program to accept RollNo from the user and display the student’s record.

Answer:

import [Link]
conn = [Link](host="localhost", user="root", password="",
database="School")
cur = [Link]()

roll = int(input("Enter Roll No to search: "))


sql = "SELECT * FROM Student WHERE RollNo = %s"
[Link](sql, (roll,))

row = [Link]()
if row:
print("Record found:", row)
else:
print("Record not found")

[Link]()

Q6. [CBSE 2020] Update student marks


Write a Python program to update the marks of the student having RollNo = 101 to 95.

Answer:

import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

sql = "UPDATE Student SET Marks = %s WHERE RollNo = %s"


data = (95, 101)
[Link](sql, data)

[Link]()
print("Record updated successfully")

[Link]()

Q7. [CBSE 2021] Delete a student record


Write a Python program to delete the record of the student having RollNo = 104.

Answer:

import [Link]
conn = [Link](host="localhost", user="root", password="",
database="School")
cur = [Link]()

sql = "DELETE FROM Student WHERE RollNo = %s"


[Link](sql, (104,))

[Link]()
print("Record deleted successfully")

[Link]()

Q8. [CBSE 2022] Display only student names


Write a Python program to display only the names of all students from the Student table.

Answer:

```python
import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

[Link]("SELECT Name FROM Student")


rows = [Link]()

for row in rows:


print(row[0])

[Link]()

Q9. [CBSE 2023] Count students with marks > 80


Write a Python program to count and display the number of students whose marks are greater
than 80.

Answer:

import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

[Link]("SELECT COUNT(*) FROM Student WHERE Marks > 80")


count = [Link]()

print("Number of students scoring > 80:", count[0])

[Link]()

Q10. [CBSE 2024] Display student records in ascending order of marks


Write a Python program to display all student records sorted by Marks in ascending order.

Answer:

import [Link]

conn = [Link](host="localhost", user="root", password="",


database="School")
cur = [Link]()

[Link]("SELECT * FROM Student ORDER BY Marks ASC")


rows = [Link]()

for row in rows:


print(row)

[Link]()

Common questions

Powered by AI

Using `executemany()` for multiple record insertions provides significant performance benefits over individual insertions by reducing the number of database connections and operations, which minimizes the transactional overhead and speeds up the process. Key impacts include: 1. Reduction in network round-trips and server processing time as multiple records are processed in a single execution. 2. Atomic operation execution, where all insertions succeed or fail together, leading to consistency in batch operations. 3. Better suited for large-scale data insertion tasks or within a transactional context where data integrity of the batch is crucial. Important considerations include ensuring that the list of data tuples is correctly formatted, understanding memory usage implications for very large data sets in memory, and handling exceptions that might arise from inserting invalid records or encountering constraints violations during batch execution .

Python and SQL integration can significantly enhance educational database management by enabling automated, efficient, and scalable operations on student data, as demonstrated by the document examples. For instance, creating tables, inserting multiple records, and updating certain fields like student marks streamline administrative processes. Administrators can easily generate reports by sorting or filtering data and ensure up-to-date information through efficient record deletion and updates, thereby improving decision-making capabilities. Furthermore, regular operations like querying for students' names or counting those above specific grade thresholds facilitate monitoring academic performance trends and identifying the need for interventions. The integration supports data integrity and reduces manual effort, offering a pathway to build more comprehensive educational tools such as learning management systems and analytics dashboards, enhancing the overall educational experience and resource management .

A Python program updates a specific record in a MySQL table by executing an `UPDATE` SQL statement, specifying the conditions to identify the record, and then committing the changes to ensure they are saved. The process involves: 1. Establishing a database connection using `mysql.connector.connect()`. 2. Creating a SQL update statement such as `UPDATE Student SET Marks = %s WHERE RollNo = %s`, using placeholders for the dynamic values. 3. Executing the statement with `cur.execute()`, passing a tuple containing the new values and condition values. 4. Committing the changes to the database using `conn.commit()` to make sure the update is saved. 5. Closing the connection with `conn.close()` after the operation is complete .

To search for a specific student record by RollNo using Python and MySQL, a program performs the following steps: 1. Connect to the MySQL database using `mysql.connector.connect()`. 2. Accept user input for `RollNo` to search. 3. Execute a `SELECT` statement with a `WHERE` clause using `cur.execute()`, like `SELECT * FROM Student WHERE RollNo = %s`, passing the user input as a parameter. 4. Use `cur.fetchone()` to retrieve the record if it exists. 5. Check if the result is `None` to handle the scenario where the record does not exist, and provide appropriate messaging (e.g., "Record not found"). 6. Print the located record if it exists. 7. Close the connection with `conn.close()` after operations are complete. This approach ensures that user input dynamically determines the search condition while handling cases where no record is found .

When writing a Python program to count and display the number of students with marks exceeding a given value using SQL, considerations include: 1. Selecting the appropriate SQL function `COUNT()` to aggregate and count rows meeting the condition. 2. Properly forming the condition in the `WHERE` clause, such as `WHERE Marks > 80`, to match the criteria accurately. 3. Using parameterized queries to prevent SQL injection if user inputs are used to specify the mark threshold. 4. Ensuring that the SQL query's performance is acceptable, particularly for large datasets, by verifying indexing on the `Marks` column. 5. Implementing error handling to manage potential database connection issues and ensuring that changes to the database schema do not affect the query assumptions. Executing `SELECT COUNT(*) FROM Student WHERE Marks > 80` and using `cur.fetchone()` to retrieve the count efficiently represents best practice .

A Python program can insert multiple records into a MySQL table using the `executemany()` method. This method allows executing a SQL command for a list of data tuples in one go, significantly reducing the number of times the server is contacted and improving efficiency. The process involves preparing a SQL insert statement with placeholders (e.g., `INSERT INTO Student VALUES (%s, %s, %s)`) and passing a list of tuples containing the records to be inserted into the `executemany()` call. The SQL command is executed for each tuple in the list, and changes are committed to the database with `conn.commit()`. The method also returns the number of records inserted, providing feedback for the operation's success .

Using Python to display the names of all students from an SQL database entails executing a `SELECT` statement that retrieves only the necessary column, which is `Name`, and efficiently handling the result set. The significance of this efficient data retrieval process includes minimizing data transfer size and improving performance. The process involves: 1. Connecting to the database via `mysql.connector.connect()`. 2. Executing the SQL query `SELECT Name FROM Student` with `cur.execute()` to fetch only the student names. 3. Using `cur.fetchall()` to retrieve all resulting rows. 4. Iterating through the results and printing each name, likely in a `for` loop. 5. Closing the database connection with `conn.close()` once the operation is completed. Efficiently querying only the required data columns reduces the overhead on the database server and network bandwidth, contributing to a more responsive application .

To securely delete a record from a MySQL table using Python, the following steps should be taken: 1. Establish a database connection using `mysql.connector.connect()`. 2. Use parameterized queries to prevent SQL injection, such as `DELETE FROM Student WHERE RollNo = %s`, and pass the RollNo as a parameter in a tuple to the `cur.execute()` method. 3. Commit the transaction with `conn.commit()` to persist the deletion in the database. 4. Careful handling involves checking the number of affected rows to confirm deletion success. 5. Close the connection with `conn.close()`. Potential risks include SQL injection if raw input is used in the query, incorrect deletions due to flawed conditional logic, or data loss without confirmation of the affected rows. Implementing proper error handling and validations minimizes these risks .

Sorting in SQL enhances the functionality of a Python program that retrieves student records by organizing the output data in a specified order, which can be more readable or meet specific requirements for data analysis or presentation. The SQL command employed is the `ORDER BY` clause, used to sort the retrieved records by one or more specified columns. In the given context, executing `SELECT * FROM Student ORDER BY Marks ASC` sorts the student records by their Marks in ascending order. This not only helps in organizing the data for better visibility but also aids in meeting specific query requirements like ranking, finding minimum or maximum values, or preparing reports from structured datasets .

A Python program can create a table in a MySQL database by using the `mysql.connector` module to establish a connection with the database, executing a SQL command to create the table, and committing the changes to the database. The process involves: 1. Importing `mysql.connector` and setting up a connection with the local MySQL server using `mysql.connector.connect()`. 2. Creating a cursor object with `conn.cursor()` to execute SQL commands. 3. Executing a SQL command using `cur.execute()` to create the table, specifying the columns and their data types (e.g., `CREATE TABLE Student (RollNo INT, Name VARCHAR(30), Marks INT)`). 4. Committing the transaction for the changes to take effect using `conn.commit()`. 5. Closing the connection with `conn.close()` to release resources after operations are complete .

You might also like