Database management SQLite and CRUD-part-IV (2)
Database management SQLite and CRUD-part-IV (2)
1. Definition:
○ A Relational Database Management System (RDBMS) is a type of database
management system that organizes data into tables (rows and columns).
○ Data in RDBMS is stored in a structured format, following relationships defined
between tables.
2. Features of RDBMS:
○ Structured Storage: Data is stored in rows (records) and columns (fields).
○ Relationships: Establishes relationships between tables using primary and
foreign keys.
○ Scalability: Suitable for large-scale applications.
○ ACID Compliance: Ensures Atomicity, Consistency, Isolation, and Durability of
database transactions.
3. Examples of RDBMS:
○ SQLite
○ MySQL
○ PostgreSQL
○ Microsoft SQL Server
○ Oracle Database
1. Definition:
○ SQL is the standard programming language used to interact with relational
databases.
○ It allows users to create, read, update, and delete (CRUD) data in a database.
2. Key SQL Operations:
○ DDL (Data Definition Language):
■ Commands like CREATE, ALTER, DROP, TRUNCATE which define the
structure of the database.
○ DML (Data Manipulation Language):
■ Commands like INSERT, UPDATE, DELETE, which manipulate the data in
the database.
○ DCL (Data Control Language):
■ Commands like GRANT, REVOKE, which control access to the database.
○ TCL (Transaction Control Language):
■ Commands like COMMIT, ROLLBACK, which manage transactions.
○ DRL (Data Retrieval Language): SELECT command, to get/read the records
from the table.
3. Advantages of SQL:
○ Easy to learn and use.
○ Widely supported across all RDBMS platforms.
○ Enables powerful querying and manipulation of data.
1. Abstraction:
Developers can focus on the application logic without worrying about the underlying
database queries.
2. Faster Development:
Eliminates repetitive SQL code, making the development process faster and more
efficient.
3. Cross-Database Compatibility:
ORM tools can work with multiple databases without requiring code changes.
4. Ease of Maintenance:
Changes to the database schema or logic can be reflected easily in the corresponding
classes.
SQLite:
● Python and Flask can connect to a variety of RDBMS software, including PostgreSQL,
MYSQL, SQLite and more.
● SQLite is a simple RDBMS software that comes with Flask and can handle all our
needs.
● SQLite(despite its name) can actually scale quite well for basic applications(100,000
hits per day)
Folder Structure:
Flask_SQLAlchemy_App
|
|--app.py
|
|--templates/
| |--index.html
|
|--app.db
Configuring Flask-SQLAlchemy:
Example 1 Basic:
app.py
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
#######################################
# Define the Student model
class Student(db.Model):
__tablename__ = "student"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
age = db.Column(db.Integer, nullable=False)
course = db.Column(db.String(50), nullable=False)
self.name = name
self.age = age
self.course = course
# db.session.add(student1)
# db.session.add(student2)
db.session.add_all([student1, student2])
db.session.commit()
● Flask: This is the Flask framework, used to create the web application.
● SQLAlchemy: This is the ORM (Object Relational Mapper) that allows us to interact
with a relational database like SQLite using Python objects instead of raw SQL
queries.
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize database
db = SQLAlchemy(app)
5. Initializing SQLAlchemy
● SQLAlchemy(app): Creates a database object (db) that we can use to define and
interact with the database.
● This line connects SQLAlchemy with the Flask app.
class Student(db.Model):
__tablename__ = "student"
7. Adding table name
● This explicitly sets the name of the database table associated with the
Student model.
● By default, SQLAlchemy automatically assigns a table name based on
the class name (Student → student in lowercase).
● But when we define __tablename__ = "student", we are manually
specifying that the table should be named "student" in the database.
def __repr__(self):
return f"<Student {self.name}>"
● Purpose: This defines how the Student object is represented when printed.
Example Usage:
python
CopyEdit
student = Student(name="Alice", age=20, course="Computer Science")
print(student) # Output: <Student Alice>
●
● This makes debugging easier.
# Create database
with app.app_context():
db.create_all()
Example 2 With os:
app.py:
basedir = os.path.abspath(os.path.dirname(__file__))
print(__file__) # e:\PythonWS\PythonApp\app.py
print(basedir) # e:\PythonWS\PythonApp
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + \
os.path.join(basedir, "app.db")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
#######################################
# Define the Student model
class Student(db.Model):
__tablename__ = "student"
self.name = name
self.address = address
self.marks = marks
# db.session.add(student1)
# db.session.add(student2)
db.session.add_all([student1, student2])
db.session.commit()
Important Point:
● For performing any insert, update and delete operation we must make use of the commit()
function, otherwise the record will not be affected.
● But for performing the select, or read operation there is no need to use the commit()
function.
● If we don’t use the basedir and use the Database URI as: sqlite:///app.db then it will
create this app.db file inside the instance folder in our application relative location.
Note: once we run the above application the app.db file will be created inside the current
working directory
● If you want to inspect your app.db SQLite file and its tables, you can use a graphical
user interface (GUI) tool.
all_students = Student.query.all()
print(all_students)
student = Student.query.get(1)
print(student)
#Note the above method is deprecated in the latest version of Flask, instead we should use
# the following method:
Example Application1:
● Create a flask application to get the students' details from the form page and after
submitting the details, store them inside the database and display all the students'
records inside a table from the database.
Folder Structure:
FlaskDatabaseApp1
|
|-- app.py
|
|-- templates/|
|
|-- base.html
|-- index.html
|-- student.html
|
|-- app.db (This will be created automatically when the database is initialized)
app.py:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + \
os.path.join(basedir, "app.db")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# Database model
class Student(db.Model):
roll = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
address = db.Column(db.String(200), nullable=False)
marks = db.Column(db.Integer, nullable=False)
def __repr__(self):
return f"Student('{self.roll}', '{self.name}', '{self.address}',
'{self.marks}')"
@app.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title_block %} {% endblock %}</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.
css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">
</head>
<body bgcolor="Cyan">
<header>
<h1 class="text-center">Welcome to Chitkara</h1>
</header>
<main>
{% block main_block %}
{% endblock %}
</main>
<footer>
<p class="text-center">© 2025 Student Information System</p>
</footer>
</body>
</html>
index.html:
{% extends "base.html" %}
{% block title_block %} Home Page {% endblock %}
{% block main_block %}
<a href="{{url_for('student')}}">Register A Student</a>
{% endblock %}
student.html:
{% extends "base.html" %}
{% block main_block %}
<h2 class="text-center">Student Registration Screen</h2>
<a href="{{url_for('index')}}">Back</a>
FlaskDatabaseApp1
|
|-- app.py
|
|-- templates/|
|
|-- base.html
|-- index.html
|-- student.html
|--update_student.html
|
|-- app.db (This will be created automatically when the database is initialized)
app.py:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + \
os.path.join(basedir, "app.db")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# Database model
class Student(db.Model):
roll = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
address = db.Column(db.String(200), nullable=False)
marks = db.Column(db.Integer, nullable=False)
# email= db.Column(db.String(100), unique=True)
def __repr__(self):
return f"Student('{self.roll}', '{self.name}', '{self.address}',
'{self.marks}')"
@app.route("/")
def index():
return render_template("index.html")
if request.method == "POST":
student.name = request.form.get("name")
student.address = request.form.get("address")
student.marks = request.form.get("marks")
db.session.commit()
return redirect(url_for('student'))
@app.route("/delete/<int:roll>")
def delete_student(roll):
student = db.session.get(Student, roll)
db.session.delete(student)
db.session.commit()
return redirect(url_for('student'))
if __name__ == '__main__':
app.run(debug=True)
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title_block %} {% endblock %}</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.
css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">
</head>
<body bgcolor="Cyan">
<header>
<h1 class="text-center">Welcome to Chitkara</h1>
</header>
<main>
{% block main_block %}
{% endblock %}
</main>
<footer>
<p class="text-center">© 2025 Student Information System</p>
</footer>
</body>
</html>
index.html:
{% extends "base.html" %}
{% block main_block %}
<a href="{{url_for('student')}}">Register A Student</a>
{% endblock %}
student.html:
{% extends "base.html" %}
{% block main_block %}
<h2 class="text-center">Student Registration Screen</h2>
<a href="{{url_for('index')}}">Back</a>
{% if students %}
<hr>
<table class="table table-primary">
<thead>
<tr>
<th>Roll Number</th>
<th>Student Name</th>
<th>Student Address</th>
<th>Student Marks</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.roll }}</td>
<td>{{ student.name }}</td>
<td>{{ student.address }}</td>
<td>{{ student.marks }}</td>
<td>
<a href="{{ url_for('update_student', roll=student.roll)
}}" class="btn btn-warning btn-sm">Update</a>
<a href="{{ url_for('delete_student', roll=student.roll)
}}" class="btn btn-danger btn-sm"
onclick="return confirm('Are you sure you want to
delete this record?')">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% endblock %}
update_student.html:
{% extends "base.html" %}
{% block main_block %}
<h2 class="text-center">Update Student Details</h2>
<a href="{{url_for('student')}}">Back</a>
<form action="{{url_for('update_student', roll=student.roll)}}"
method="POST">
<div class="form-group">
<label for="roll">Roll Number</label>
<input type="number" class="form-control" id="roll" name="roll"
value="{{ student.roll }}" disabled>
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name"
value="{{ student.name }}" required>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address"
name="address" value="{{ student.address }}" required>
</div>
<div class="form-group">
<label for="marks">Marks</label>
<input type="number" class="form-control" id="marks" name="marks"
value="{{ student.marks }}" required>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
{% endblock %}