Performing CRUD Operations With SQLAlchemy
00:00 In previous lessons, you worked with raw SQL and SQLite. In this section, you’re going to explore how to perform the same operations using Python objects.
00:10
In order to get started, you need to initialize an interactive REPL session by typing python in your terminal window. Next, you import the classes and functions you’ll need. These include Session, Bird, and init_db().
00:27
You can call init_db() to initialize the database. The session is going to be your main interface for interacting with the database.
00:38
Next, you’ll create a new Python object that represents a bird. Let’s call it "Test Bird". You can add it to the database by executing session.add() and specifying your Python object, new_bird. To write the new record to the database and make the change permanent, you need to call session.commit().
01:01
Now that you’ve created a new database entry using SQLAlchemy, let’s look at how to retrieve it. You’ll begin by importing select from sqlalchemy, which allows you to build a query to fetch your records. Next, you’ll create a query object using select(Bird) and filter it by referencing the bird’s name.
01:22
So here, you’ll set the name to "Test Bird", which will tell SQLAlchemy that you only want to retrieve birds with this exact name. You can run your query with session.execute() and call .scalar_one() to return a single matching row as a Python object.
01:41
So now printing the word bird will show the Bird object, which can now be used directly in Python.
01:49
To update a record, you can simply modify the object’s attribute. Here you can change the bird’s name from "Test Bird" to "Example Bird".
01:59
Let’s save this update by calling session.commit(). And run the select query again to verify that your update worked.
02:11
To delete a record, you pass the object you want to remove, in this case bird, to session.delete(). Then call session.commit() and session.close() to close the session and database connection.
02:27 With all four CRUD operations complete, you can now see how Python objects make database interactions structured and easy to manage.
02:38 In this lesson, you’ve learned how to work with SQLAlchemy and Python objects instead of writing raw SQL. You’ve seen how to perform all four CRUD operations with SQLAlchemy. And you also learned how to work with sessions to manage database interactions.
02:54 And finally, you’ve seen how SQLAlchemy converts what would normally be raw SQL into clear and readable Python code, making database interactions much easier to work with.
Become a Member to join the conversation.
