CBSE Class 12 Computer Science
SQL and Its Interface with Python
1. Introduction to SQL (Structured Query Language)
SQL is a standard language for storing, manipulating, and retrieving data in databases. It is
used to communicate with relational database systems like MySQL, SQLite, etc.
Key SQL commands include: SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, etc.
2. Common SQL Commands and Examples
a. CREATE TABLE
CREATE TABLE Student (
RollNo INT,
Name VARCHAR(50),
Marks INT
);
b. INSERT INTO
INSERT INTO Student VALUES (101, 'Amit', 85);
c. SELECT
SELECT * FROM Student;
SELECT Name, Marks FROM Student WHERE Marks > 80;
d. UPDATE
UPDATE Student SET Marks = 90 WHERE RollNo = 101;
e. DELETE
DELETE FROM Student WHERE RollNo = 101;
3. SQL Interface with Python (Using SQLite3)
Python provides sqlite3 module to interact with SQLite databases. Other databases like
MySQL can be accessed using modules like mysql.connector or SQLAlchemy.
Steps to use SQL in Python:
1. Import sqlite3
2. Connect to database
3. Create cursor
4. Execute SQL command
5. Commit (if needed)
6. Close connection
Example:
import sqlite3
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Student (RollNo INT, Name TEXT, Marks
INT)")
cursor.execute("INSERT INTO Student VALUES (101, 'Amit', 85)")
cursor.execute("SELECT * FROM Student")
for row in cursor.fetchall():
print(row)
conn.commit()
conn.close()
4. CBSE Board PYQs on SQL and Python Interface
Q1. Write SQL command to display names of students who have scored more than 80
marks.
Answer:
SELECT Name FROM Student WHERE Marks > 80;
Q2. Write Python code to create a table "Teacher" with fields ID and Name.
import sqlite3
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE Teacher (ID INT, Name TEXT)")
conn.commit()
conn.close()
Q3. Write the output of the following SQL query:
SELECT Name FROM Student WHERE Marks BETWEEN 70 AND 90;
Answer: Displays names of students whose marks are between 70 and 90.