Sim Mautner
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: 8 - Databases tags: COMP1010 slideOptions: transition: slide --- <style> .reveal { font-size: 26px; } .reveal div.para { text-align: left; } .reveal ul { display: block; } .reveal ol { display: block; } </style> # COMP1010 ## 8 - Databases --- # Databases Introduction A database is an organized collection of data stored and accessed electronically from a computer system. --- ## Why Use Databases? * Persistence (so we don't lose our data when the application closes) (just like saving in a file). * It allows us to access and summarize data more quickly/simply/easily. --- Side Note: Databases are a great skill to have outside of what's generally considered 'programming'. There are database applications which use SQL but do not require other programming skills. In these cases, it is useful, in life and workplace, to understand and be able to use/look up how to do things. --- ## SQL * SQL (Structured Query Language) is a standard language for accessing and manipulating databases. * There are different versions, but major (most commonly used) commands are supported in similar ways. * We will use sqlite3 in this course as it comes packaged with Python and does not require its own server running. Most of the skills you learn, can be adapted to any other SQL database. --- ## Terminology * table: a collection of related data entries * field: a column of a table * record (or entry): a row of a table --- ## Notes * A database consists of one or more tables. * Much like a variable, each field (or column) has a name, and a type. * You can think of a database table as a list (lots of rows) of dictionaries (each column is a part of the dictionary) in Python. --- ## Approximate Roadmap * Each demo builds on the one before. * Sometimes we will improve an approach, so remove old code and replace it with better code. * Sometimes we will only add new code to add functionality to the program. * Demo 10 contains the best of our code, and all the functionality from earlier demonstrations. --- ## Approximate Roadmap 1. Creating tables. (1-2) 2. Inserting data into the tables. (3,6,8) 3. Primary keys. (4-5) 4. Foreign keys. (7) 5. Getting data from tables. (10) --- ## Types of Demos * Demos - Python code showing how to use your database from a Python program. * Direct to the database - Accessing the database directly to: * check our Python code is working * learn SQL * build familiarity with databases --- ## Demo Introduction * Splitting the bill: Look over spreadsheet version --- ## Demos * Aside: Draw a diagram for `groups` table. * 1 - Create a table of `groups`. Each group should have a unique name. * What happens if we try to create a table which already exists? * How can we fix this? * 2 - Create a table with IF NOT EXISTS to avoid the problem in `demo_1.py`. --- ## Direct to the database: Inspecting Command-line commands (for use in the terminal): * Connect to the database: `sqlite3 split_the_bill.db` * Get table names: ```sql select name from sqlite_master where type="table"; ``` * Get table schema (structure): `.schema groups` * ctl-D to exit command-line connection * Up-Arrow scrolls through previous commands --- ## Direct to the database: SELECT and INSERT INTO * `*` means 'all' * `--` creates a comment ```sql -- Get all rows and columns from a table SELECT * from table_name; -- Get only the listed fields (columns) from a table SELECT field_1_name, field_2_name, ... from table_name; -- Get all fields (columns) from a table, where the condition is met SELECT * from table_name WHERE field_name = 'value'; -- Insert the values into the table (must list all the fields, in the correct order) INSERT INTO table_name VALUES (field_1_value, field_2_value, ...); -- Insert the values into the table where you only have some fields to put in INSERT INTO table_name (field_1_name, field_2_name, ...) VALUES (field_1_value, field_2_value, ...); ``` --- ## Demos * 3 - Insert some groups into the table. * What happens if we try and insert a group with a name which is already used? * How can we address this? (We wanted group names to be unique.) --- ## Primary Keys * Used to make each row uniquely identifiable * Like a row number in a spreadsheet * Must be unique * Can be automatically generated (for more information, look [here](https://www.tutorialspoint.com/sqlite/sqlite_using_autoincrement.htm)) * Can be made up of more than one field * To make a field a primary key, add `PRIMARY KEY` to the end of its declaration. * To make a composite primary key, add a line to the table creation `PRIMARY KEY (field_1, field_2...)` at the end of the table creation. --- ## Demos * 4 - Delete your existing database. Change demo 3, but make it so that the `name` field of the `groups` table is a primary key. * What happens *now* when you try to insert the same value multiple times? * 5 - Change demo 4 so that it elegantly handles the `sqlite3.IntegrityError` exception that was raised if someone tries to insert the same group multiple times. * Aside: Draw a diagram for People table and Menu_Items table. * people: name as primary key, p_group, amount they've paid (NOTE: we can't use `group` as a column name because it's a keyword in SQL.) * menu_items: name and mi_group create the primary key, price, quantity * 6 - Create a full set of tables for Splitting the Bill. Insert some people into the `people` table. * What happens if you give someone a group name which doesn't exist? * Can we enforce assigning people only to groups which currently exist? --- ## Foreign Keys * Used when a field in one table references a field in another table. * Make sure your database is enforcing foreign keys: ```sql c.execute("PRAGMA foreign_keys = ON") db.commit() ``` * Make a field a foreign key: ```sql FOREIGN KEY (field_name) REFERENCES table_name (other_field_name) ``` --- ## Demos * 7 - Update `demo_6.py` so that only groups already in the `groups` table can be used in the `people` and `menu_items` tables. * 8 - Populate the tables with some sample data. * 9 - Refactor your code (if you haven't already) from `demo_8.py` to make it ready to be used in a bigger application. --- ## Accessing Information and Using It Looking back at week 1, what information would be useful to get from our database? * The size of each group. * The amount spent by each group. --- Keeping your application in its improved layout, implement the functionality listed below. * 10 - Write the following functions: * Get all the groups (into a dictionary). `get_all_groups()` * Get all the people (into a dictionary). `get_all_people()` * Get all the menu items (into a dictionary). `get_all_menu_items()` --- * Update the groups dictionary to include the size of each group. `calculate_groups_sizes(groups)` * Get all the people for a given group. `get_all_people_for_group(group_name)` * Get the size of a given group. `get_size_of_group(group_name)` --- * Update the groups dictionary to include the total spent for each group. `calculate_groups_total_spent(groups)` * Get all the menu items for a given group. `get_all_menu_items_for_group(group_name)` * Get the total spent for a given group. `get_total_spent_for_group(group_name)` --- * Fill out the people list with the amount they owe. (Initial owing, minus what they have already paid.)`calculate_people_owing(groups, people)` * Update table and dictionary with amount that someone has paid. `add_payment(person_name, payment_amount)` --- ## Another Example: * Tutorials: course_code, code, tutor * Courses: course_code, title * Students: zid, fname, lname * Enrollments: course_code, tute_code, zid --- ## Extra Resources: * [SQL Commands - Interactive](https://www.w3schools.com/sql/default.asp) * [SQLite3 Documentation](https://docs.python.org/3/library/sqlite3.html) * [SQLite Tutorial - Interactive](https://www.sqlitetutorial.net/sqlite-select/) --- ## Feedback Lecture: 8 - Databases ![](https://i.imgur.com/5FKvgmw.png) [Link to feedback form](https://forms.gle/NdAhw7ZMJ2eBEydd7)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully