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.
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.
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 bookdescription where we will store a description for our bookcover where we will store the URL of a cover image for our bookreason where we will store the reason why this is a recommended bookcreated_at for the date we added the bookThen exit the sqlite prompt:
.exit
You should now have a file named books.db alongside your app.py file.
Please give a thumbs up or chat message when you’ve successfully created your books database.
When we complete saving all data to the database the book table will look something like this:
| id | title | description | cover | reason | created_at |
|---|---|---|---|---|---|
| 1 | Book title 1 | This is a description for book 1 | https://bookimages.com/book1_image.jpg | This is a reason for book 1 | 2022-07-22 |
| 2 | Book title 2 | This is a description for book 2 | https://bookimages.com/book2_image.jpg | This is a reason for book 2 | 2022-07-23 |
| 3 | Book title 3 | This is a description for book 3 | https://bookimages.com/book3_image.jpg | This is a reason for book 3 | 2022-07-23 |