Intro to Coding
  • Unit 1
    • Introduction
  • Activity 1.1
  • Activity 1.2
  • Activity 1.3
  • Activity 1.4
  • Activity 1.5
  • Activity 1.6
  • Activity 1.7
  • Activity 1.8
  • Activity 1.9
  • Activity 1.10
  • Activity 1.11
  • Activity 1.12
  • Activity 1.13
  • Project 1
  • Activity 1.14
  • Activity 1.15
  • Activity 1.16
  • Activity 1.17
  • Activity 1.18
  • Activity 1.19
  • Activity 1.20
  • Activity 1.21
  • Activity 1.22
  • Activity 1.23
  • Activity 1.24
  • Activity 1.25
  • Activity 1.26
  • Project 2
  • Activity 1.27
  • Activity 1.28
  • Activity 1.29
  • Activity 1.30
  • Unit 2
    • Introduction
  • Activity 2.1
  • Activity 2.2
  • Activity 2.3
  • Project 3
  • Activity 2.4
  • Activity 2.5
  • Activity 2.6
  • Activity 2.7
  • Project 4
  • Activity 2.8
  • Activity 2.9
  • Activity 2.10
  • Activity 2.11
  • Activity 2.12
  • Activity 2.13
  • Activity 2.14
  • Activity 2.15
  • Activity 2.16
  • Activity 2.17
  • Activity 2.18
  • Activity 2.19
  • Activity 2.20
  • Activity 2.21
  • Activity 2.22
  • Activity 2.23
  • Project 5
  • Activity 2.24
  • Activity 2.25
  • Activity 2.26
  • Unit 3
    • Introduction
  • Activity 3.1
  • Activity 3.2
  • Activity 3.3
  • Activity 3.4
  • Activity 3.5
  • Activity 3.6
  • Activity 3.7
  • Activity 3.8
  • Activity 3.9
  • Activity 3.10
  • Activity 3.11
  • Activity 3.12
  • Project 6
  • Activity 3.13
  • Activity 3.14
  • Activity 3.15
  • Activity 3.16
  • Activity 3.17
  • Activity 3.18
  • Activity 3.19
  • Activity 3.20
  • Activity 3.21
  • Activity 3.22
  • Activity 3.23
  • Project 7
  • Activity 3.24
Powered by GitBook
On this page
  • Source Code
  • Join Query

Activity 2.17

Source Code

import sqlite3

def create_connection(db_file="activity217.db"):
    """Create a database connection to the SQLite database specified by db_file."""
    connection = None
    try:
        connection = sqlite3.connect(db_file)
        print("Connection to SQLite DB successful")
    except sqlite3.Error as e:
        print(f"Error '{e}' occurred while connecting to database")
    return connection

def create_students_table(connection):
    """Create the Students table if it doesn't exist."""
    cursor = connection.cursor()
    query = """
    CREATE TABLE IF NOT EXISTS Students (
        student_id INTEGER PRIMARY KEY AUTOINCREMENT,
        first_name TEXT NOT NULL,
        last_name  TEXT NOT NULL
    );
    """
    cursor.execute(query)
    connection.commit()
    print("Students table created successfully.")

def create_grades_table(connection):
    """Create the Grades table if it doesn't exist, referencing the Students table."""
    cursor = connection.cursor()
    query = """
    CREATE TABLE IF NOT EXISTS Grades (
        grade_id   INTEGER PRIMARY KEY AUTOINCREMENT,
        student_id INTEGER NOT NULL,
        subject    TEXT NOT NULL,
        grade      TEXT NOT NULL,
        FOREIGN KEY(student_id) REFERENCES Students(student_id)
    );
    """
    cursor.execute(query)
    connection.commit()
    print("Grades table created successfully.")

def insert_student(connection, first_name, last_name):
    """Insert a new student record."""
    cursor = connection.cursor()
    query = """
    INSERT INTO Students (first_name, last_name)
    VALUES (?, ?);
    """
    cursor.execute(query, (first_name, last_name))
    connection.commit()
    print(f"Inserted student: {first_name} {last_name}")

def insert_grade(connection, student_id, subject, grade):
    """Insert a new grade record linked to a student_id."""
    cursor = connection.cursor()
    query = """
    INSERT INTO Grades (student_id, subject, grade)
    VALUES (?, ?, ?);
    """
    cursor.execute(query, (student_id, subject, grade))
    connection.commit()
    print(f"Inserted grade: Student={student_id}, Subject={subject}, Grade={grade}")

def main():
    # 1. Connect to or create the database
    conn = create_connection("activity217.db")

    # 2. Create the necessary tables
    create_students_table(conn)
    create_grades_table(conn)

    # 3. Insert some sample students
    insert_student(conn, "Alice", "Brown")   # student_id = 1 (AUTOINCREMENT)
    insert_student(conn, "Bob", "Smith")     # student_id = 2 (AUTOINCREMENT)
    insert_student(conn, "Charlie", "Davis") # student_id = 3 (AUTOINCREMENT)

    # 4. Insert some grades for the students
    insert_grade(conn, 1, "Math", "A")
    insert_grade(conn, 1, "English", "B+")
    insert_grade(conn, 2, "Math", "B-")
    insert_grade(conn, 3, "History", "A")

    # 5. Fetch and display the joined results from both tables
    cursor = conn.cursor()
    cursor.execute(
        """
        SELECT s.student_id, s.first_name, s.last_name, g.subject, g.grade
        FROM Grades AS g
        INNER JOIN Students AS s
            ON g.student_id = s.student_id
        ORDER BY s.student_id;
        """
    )

    rows = cursor.fetchall()
    print("\n--- Joined Results from Students and Grades ---")
    for row in rows:
        print(row)

    # 6. Close the database connection when done
    conn.close()
    print("\nDatabase connection closed.")

main()

Join Query

SELECT 
    Students.student_id,
    Students.first_name,
    Students.last_name,
    Grades.subject,
    Grades.grade
FROM Students
INNER JOIN Grades
    ON Students.student_id = Grades.student_id;
PreviousActivity 2.16NextActivity 2.18

Last updated 3 months ago