Python and SQL
Objectives
- Set up and interact with an SQLite3 database using Python
- Create tables (
Students
andClasses
), insert data, and establish relationships. - Query the database to retrieve, update, and manage data.
SQLite3 and Python Tutorial: Managing Students and Classes
Prerequisites:
To follow along with this tutorial the following software and knowledge will be needed:
- Install Python (version 3 or higher) on your system.
- Ensure you have the
sqlite3
library (it comes pre-installed with Python). - Basic knowledge of Python syntax.
Part 1: Setting Up the Database
Step 1: Importing SQLite3 in Python
import sqlite3
allows you to use the SQLite3 database engine in Python. SQLite3 is a lightweight, file-based database system, ideal for small projects.
Step 2: Creating a Connection to SQLite Database
sqlite3.connect('school.db')
creates or connects to a database file called school.db. If the file doesn't exist, it will be created in the current directory.cursor = conn.cursor()
creates a cursor object, which is used to execute SQL commands and interact with the database.
Part 2: Creating Tables for Students
and Classes
Step 3: Creating the Students
Table
CREATE TABLE IF NOT EXISTS Student
creates a table calledStudent
if it doesn't already exist. The table contains three columns or fields:StudentID
(unique identifier),StudentName
, andAge
.PRIMARY KEY
definesStudentID
as a unique identifier for each student.
Step 4: Creating the Class
Table
- This step creates a
Class
table with four columns:ClassID
(unique identifier for the class),ClassName
,Teacher
, andRoomNumber
.
Warning
The identifier for each field must be a whole word, no spaces. Think of it like an identifier for a variable and follow the same rules.
Step 5: Creating the Enrollment
Table (Linking Table)
- This table links the Student and Class tables.
FOREIGN KEY
is used to establish relationships betweenStudentID
in theEnrollment
table andStudentID
in theStudent
table, and betweenClassID
inEnrollment
andClassID
in theClass
table. This allows us to relate students to their classes.
Part 3: Inserting Data into the Tables
Step 6: Inserting Data into the Students
Table
cursor.executemany()
is used to insert multiple rows into the Student table. Each tuple in the students list contains values forStudentID
,StudentName
, andAge
.
Step 7: Inserting Data into the Classes
Table
- Similar to the previous step,
executemany()
inserts multiple rows into theClass
table. Each tuple contains the class details (ClassID
,ClassName
,Teacher
, andRoomNumber
).
Step 8: Inserting Data into the Enrollment
Table (Linking Table)
- This step links students to the classes they are enrolled in. Each tuple contains a StudentID and a ClassID, establishing relationships between students and their classes.
Part 4: Querying the Database
Step 9: Retrieving Students and Their Enrolled Classes
To fetch data, we can use a JOIN
query that links the Students
and Classes
tables via the Enrollment
table.
- The
JOIN
query connects theEnrollment
,Student
, andClass
tables to retrieve information about which students are enrolled in which classes.
Expected Output:
Step 10: Retrieving Students in a Specific Class
Let's fetch the list of students enrolled in a specific class (e.g., Maths
).
- This query uses a
WHERE
clause to filter students who are enrolled in a particular class (e.g., C001 for Maths).
Expected Output:
Part 5: Updating and Deleting Data
Step 11: Updating Student Information
UPDATE
is used to change data in theStudent
table. Here, we update the age of a student named "Jane Roe."- After executing the update query, we use
SELECT
to verify that the change has been applied.
Step 12: Deleting a Student Record
DELETE
removes a record from theStudent
table. In this case, we delete "Sam White" by specifying their name in theWHERE
clause.
Part 6: Closing the Database Connection
conn.close()
closes the connection to the database. This is important to free up resources and ensure that no uncommitted changes are lost.
Summary:
In this tutorial, you’ve learned to:
- Set up a relational database with SQLite3 using Python.
- Create and populate tables (
Students
,Classes
,Enrollment
). - Use SQL queries to retrieve, update, and delete data.
- Understand how tables relate to each other using primary and foreign keys.