Introduction to SQL

SQL - Chapter 1

We appreciate your patience while we actively develop and enhance our content for a better experience.

Sample Code
import sqlite3

def main():
    print("This program demonstrates how to use SQLite to create a database, create a table, insert data, and query data from the table.")

    # Connect to a database (it will be created if it doesn't exist)
    conn = sqlite3.connect('students.db')
    cursor = conn.cursor()

    # Create a table for student grades
    cursor.execute('''CREATE TABLE IF NOT EXISTS student_grades (
                        id INTEGER PRIMARY KEY,
                        name TEXT,
                        math INTEGER,
                        science INTEGER,
                        english INTEGER)''')
    
    # Insert sample data
    students = [
        ('Alice', 85, 90, 82),
        ('Bob', 78, 82, 91),
        ('Charlie', 92, 88, 78),
        ('David', 76, 75, 88),
        ('Eva', 89, 93, 80)
    ]

    cursor.executemany('INSERT INTO student_grades (name, math, science, english) VALUES (?, ?, ?, ?)', students)
    conn.commit()

    print("Data inserted successfully.")

    # Query data from the table
    cursor.execute('SELECT * FROM student_grades')

    print("\nStudent grades:")
    print("ID | Name     | Math | Science | English")
    for row in cursor.fetchall():
        print(f"{row[0]}  | {row[1]:<7} | {row[2]:<4} | {row[3]:<6} | {row[4]}")

    # Close the connection
    conn.close()

if __name__ == "__main__":
    main()