from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
def init_db():
with sqlite3.connect('students.db') as conn:
conn.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL,
course TEXT NOT NULL)''')
init_db()
@app.route('/')
def index():
with sqlite3.connect('students.db') as conn:
students = conn.execute("SELECT * FROM students").fetchall()
return render_template('index.html', students=students)
@app.route('/add', methods=['GET', 'POST'])
def add_student():
if request.method == 'POST':
name = request.form['name']
age = request.form['age']
course = request.form['course']
with sqlite3.connect('students.db') as conn:
conn.execute("INSERT INTO students (name, age, course) VALUES (?, ?, ?)",
(name, age, course))
conn.commit()
return redirect(url_for('index'))
return render_template('add_student.html')
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update_student(id):
if request.method == 'POST':
name = request.form['name']
age = request.form['age']
course = request.form['course']
with sqlite3.connect('students.db') as conn:
conn.execute("UPDATE students SET name=?, age=?, course=? WHERE id=?",
(name, age, course, id))
conn.commit()
return redirect(url_for('index'))
with sqlite3.connect('students.db') as conn:
student = conn.execute("SELECT * FROM students WHERE id=?", (id,)).fetchone()
if not student:
return "Student not found", 404
return render_template('update_student.html', student=student)
@app.route('/delete/<int:id>')
def delete_student(id):
with sqlite3.connect('students.db') as conn:
conn.execute("DELETE FROM students WHERE id=?", (id,))
conn.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)