- Home
- Javascript
- Creating the Database and Tables
Creating the Database and Tables
Contents
Creating the Database and Tables
The next step is setting up how the program connects to the database, and creating the tables that will actually hold the data.
def connect_db():
conn = sqlite3.connect("school.db")
return connThis connect_db() function opens a connection to a file called school.db. If this file doesn't exist yet, SQLite creates it automatically the first time the program runs. This function gets called every time any part of the program needs to talk to the database.
def create_tables():
conn = connect_db()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INTEGER PRIMARY KEY,
name TEXT NOT NULL,
class_name TEXT,
age INTEGER,
phone TEXT
)
""")This creates the students table, where roll_no is set as the primary key, meaning every student must have a unique roll number, and no two students can share the same one.
cur.execute("""
CREATE TABLE IF NOT EXISTS attendance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
roll_no INTEGER,
date TEXT,
status TEXT,
FOREIGN KEY (roll_no) REFERENCES students (roll_no)
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS grades (
id INTEGER PRIMARY KEY AUTOINCREMENT,
roll_no INTEGER,
subject TEXT,
marks INTEGER,
FOREIGN KEY (roll_no) REFERENCES students (roll_no)
)
""")
conn.commit()
conn.close()The attendance and grades tables both use roll_no as a foreign key, linking every attendance entry or mark back to a specific student in the students table. conn.commit() saves these changes permanently, and conn.close() closes the connection so the database file isn't left open unnecessarily.
Student Management System using Python (Beginner-Friendly Project Guide)
Abhishek Pati








