You are on page 1of 3

Hopefully, you figured out how to solve the challenge from the last lesson, as a review,

here's a summary of some of the things we did:

Create a New Database

1. from flask import Flask


2. from flask_sqlalchemy import SQLAlchemy
3. app = Flask(__name__)
4. app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///<name of database>.db"
5. db = SQLAlchemy(app)

Create a New Table

1. class Book(db.Model):
2. id = db.Column(db.Integer, primary_key=True)
3. title = db.Column(db.String(250), unique=True, nullable=False)
4. author = db.Column(db.String(250), nullable=False)
5. rating = db.Column(db.Float, nullable=False
6.  
7. db.create_all()

In addition to these things, the most crucial thing to figure out when working with any
new database technology is how to data records.

Create

Read

Update

Delete

So, let's go through each of these using SQLite and SQLAlchemy:

Create A New Record

1. new_book = Book(id=1, title="Harry Potter", author="J. K. Rowling",


rating=9.3)
2. db.session.add(new_book)
3. db.session.commit()

NOTE: When creating new records, the primary key fields is optional. you can also write:

new_book = Book(title="Harry Potter", author="J. K. Rowling",


rating=9.3)

the  id  field will be auto-generated.

Read All Records

1. all_books = session.query(Book).all()

Read A Particular Record By Query

1. book = Book.query.filter_by(title="Harry Potter").first()

Update A Particular Record By Query

1. book_to_update = Book.query.filter_by(title="Harry Potter").first()


2. book_to_update.title = "Harry Potter and the Chamber of Secrets"
3. db.session.commit()

Update A Record By PRIMARY KEY

1. book_id = 1
2. book_to_update = Book.query.get(book_id)
3. book_to_update.title = "Harry Potter and the Goblet of Fire"
4. db.session.commit()

Delete A Particular Record By PRIMARY KEY

1. book_id = 1
2. book_to_delete = Book.query.get(book_id)
3. db.session.delete(book_to_delete)
4. db.session.commit()

You can also delete by querying for a particular value e.g. by title or one of the other
properties.

You might also like