Skip to main content

CRUD Operations

All database operations are performed using a Session.

Create a Session

File: database.py

File: main.py

Create (Insert)

File: main.py

Explanation

Creates a new Student object.
Adds the object to the Session.
Saves the object to the database.

Read (Select)

File: main.py

Explanation

Creates a query to retrieve all students.
Executes the query and returns a Result object.
Extracts the Student objects and returns them as a Python list.

Update

File: main.py

Explanation

Retrieves the student whose primary key is 1.
Updates the object’s attributes.
Saves the changes to the database.

Alternative (Direct Query)

Delete

File: main.py

Explanation

Retrieves the student to be deleted.
Marks the object for deletion.
Removes the record from the database.

Alternative (Direct Query)

Rollback Changes

File: main.py

Explanation

Discards all uncommitted changes if an error occurs.

Close the Session

File: main.py

Explanation

Closes the Session and releases the database connection.

Quick Revision

Note: The object-based approach is the recommended way to work with SQLAlchemy ORM. Direct update() and delete() statements are useful for bulk operations and will be covered in detail in the Advanced Queries chapter.