From the course: Advanced Python: Practical Database Examples

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Add data to a database in Python using SQLAlchemy

Add data to a database in Python using SQLAlchemy - Python Tutorial

From the course: Advanced Python: Practical Database Examples

Add data to a database in Python using SQLAlchemy

- [Instructor] Before we can add data dynamically to our database, we need to create an easy way for an outside module to interact with it. In this case, an easy way for an outside module, to add a book. Let's create an addBook function to our database.py file. Eventually, this will be used by the main.py application to add a book to the database. It'll take in a book and an author. Now, to interact with the database we'll need to start a session. In this function, we have three tasks, update the book table, update the author table and update the pairings table. We also don't want to add any data that already exists. This means before we add data we should run a query to check if the data already exists in the database. We'll start with our book data. With SQL Alchemy, we can use the select function and filter where the book data is the same as the data passed in. Here, we select a book where the title is the same as…

Contents