Create Database

We have an application that shows the user some text that we control, but we want our application to be able to take in data submitted by a user, save it and then display it back to users. To do this, we need to do some preliminary setup, and create a database.

Create Database File

Open a new terminal window tab (open your Terminal window, then press CMD+t on Mac / CTRL+Shift+4 on Windows). You should see multiple tabs open in your terminal window. To switch between tabs, you can click on each tab near the top of the terminal window, just like in your web browser.

Change into your project directory:

cd ~/Desktop/jumpstart-2022/jumpstart-webdev

and run: sqlite3 books.db

This will create a new, empty sqlite database. In the case of sqlite this is just a file alongside your other files for this project. After you run this command, you will see sqlite> and a flashing cursor beside it - you are in the “sqlite prompt”, which is a program that lets you type and run SQL commands to interact with your database.

Create Database Structure

In the sqlite prompt enter:

CREATE TABLE book (id INTEGER PRIMARY KEY, title TEXT, description TEXT, cover TEXT, reason TEXT, created_at timestamp);

Here we’re using SQL to create a table named “book” with 6 columns:

  • id an integer and also the primary key (a unique identifier for the record of the book in the database)
  • title for where we will store the title of our book
  • description where we will store a description for our book
  • cover where we will store the URL of a cover image for our book
  • reason where we will store the reason why this is a recommended book
  • created_at for the date we added the book

Then exit the sqlite prompt: .exit

You should now have a file named books.db alongside your app.py file.

When we complete saving all data to the database the book table will look something like this:

idtitledescriptioncoverreasoncreated_at
1Book title 1This is a description for book 1https://bookimages.com/book1_image.jpgThis is a reason for book 12022-07-22
2Book title 2This is a description for book 2https://bookimages.com/book2_image.jpgThis is a reason for book 22022-07-23
3Book title 3This is a description for book 3https://bookimages.com/book3_image.jpgThis is a reason for book 32022-07-23