1 May 2024
CT4029
Principles of Programming
Week 5
SQLite Database in Python
Learning Outcomes
Understanding of databases
How to design a database
o Assigning keys
o Relationships
Querying databases
Interacting with databases using Python
2
Today’s Agenda!
• Relational Databases
• Create Read Update Delete
• Databases in Python
3
DB Browser for SQLite
4
DB Browser for SQLite – Free Tool
https://sqlitebrowser.org/
https://sqlitebrowser.org/blog/version-3-12-2-released/
Please check Moodle Week 5 for the .zip file of DB Browser
5
Relational Database
6
Relational Databases
Relational databases model data by storing rows and columns in tables. The
power of the relational database lies in its ability to efficiently retrieve data from
those tables and in particular where there are multiple tables and the
relationships between those tables involved in the query.
http://en.wikipedia.org/wiki/Relational_database
7
Terminology (1/3)
• Database – contain tables
• Relation (tables) – contains tuples and attributes
• Tuple (or row) – a set of fields that generally represents an “object” like a
person or a music track
• Attribute (also column or field) – one of possibly many elements of data
corresponding to the object represented by the row
8
Terminology (2/3)
A relation is defined as a set of tuples that have the same attributes. A tuple usually
represents an object and information about that object. Objects are typically
physical objects or concepts. A relation is usually described as a table, which is
organized into rows and columns. All the data referenced by an attribute are in the
same domain and conform to the same constraints. (Wikipedia)
9
Terminology (3/3)
Table/Relation
Columns/
Attributes
Tuples/
Rows
10
Two Roles in Large Projects
Application Developer:
• Builds the logic for the application, the look and feel of the application
• Monitors the application for problems
Database Administrator:
• Monitors and adjusts the database as the program runs in production
Often both people participate in the building of the “Data model”
11
Database Model
A database model or database schema is the structure or format of a
database, described in a formal language supported by the database
management system, In other words, a “database model” is the application of
a data model when used in conjunction with a database management system.
http://en.wikipedia.org/wiki/Database_model
12
Database Design
• Database design is an art of its own with particular skills and experience
• Our goal is to avoid the really bad mistakes and design clean and easily
understandable databases
• Others may performance tune things later
• Database design starts with a picture...
13
Building a Data Model
• Drawing a picture of the data objects for our application and then figuring
out how to represent the objects and their relationships
• Basic Rule: Don’t put the same string data in twice - use a relationship
instead
• When there is one thing in the “real world” there should be one copy of that
thing in the database
14
Key Types
• Primary Key – generally an integer auto-increment field
• Logical key - What the outside world uses for lookup
• Foreign key - generally an integer key pointing to a row in another table
15
Primary Key Rules
Best practices
Never use your logical key as the primary key
Logical keys can and do change, albeit slowly
Relationships that are based on matching string fields are less efficient than
integers
16
Foreign Keys
A foreign key is when a table has a column that contains a key which points
to the primary key of another table.
When all primary keys are integers, then all foreign keys are integers
17
Relationship Building (in tables)
Artist Track
id Album id
name title
id
title rating
Table artist_id len
Primary key count
album_id
Logical key
genre_id
Foreign key Genre
id
Naming FK artist_id is a
convention name
18
Relationship Types: One-to-One (1/8)
You share many relationships with members of your family. For instance, you and your
mother are related. You have only one mother, but she may have several children. You and
your siblings are related—you may have many brothers and sisters and, of course, they'll
have many brothers and sisters as well. If you're married, both you and your spouse have a
spouse—each other—but only one at a time. Database relationships are very similar in that
they're associations between tables. There are three types of relationships
One-to-One
One-to-Many
Many-to-Many
19
Relationship Types: One-to-One (2/8)
One-to-one: Both tables can have only one record on either side of the
relationship. Each primary key value relates to only one (or no) record in the
related table. They're like spouses—you may or may not be married, but if you
are, both you and your spouse have only one spouse. Most one-to-one
relationships are forced by business rules and don't flow naturally from the
data. In the absence of such a rule, you can usually combine both tables into
one table without breaking any normalization rules.
20
Relationship Types: One-to-Many (3/8)
One-to-many: The primary key table contains only one record that relates to
none, one, or many records in the related table. This relationship is similar to
the one between you and a parent. You have only one mother, but your mother
may have several children.
21
Relationship Types: One-to-Many: Example (4/8)
Track Review:
belongs-to One to Many
Title
Album
One Many Rating
Len
Count Track
Table id
Primary key Album
Logical key One title
Foreign key id rating
title len
Many
count
album_id
22
Relationship Types: One-to-Many: Example (5/8)
One Many
One
Many
23
Relationship Types: Many-to-Many (6/8)
Many-to-many: Each record in both tables can relate to any number of
records (or no records) in the other table. For instance, if you have several
siblings, so do your siblings (have many siblings). Many-to-many relationships
require a third table, known as an associate or linking table, because relational
systems can't directly accommodate the relationship.
24
Relationship Types: Many-to-Many (7/8)
Sometimes we need to model a relationship that is many-to-many
We need to add a "connection" table with two foreign keys
There is usually no separate primary key
25
Relationship Types: Many-to-Many (8/8)
member-of
User
Course
title Many Many name
email
User
Course Member
Many id
id user_id
Many One name
title One course_id
email
26
SQLite – DB Browser
27
SQL
Structured Query Language is the language we use to issue commands to the
database:
• Create a table
• Retrieve some data
• Insert data
• Delete data
28
SQLite Browser
SQLite is a very popular database - it is free and fast and small
SQLite Browser allows us to directly manipulate SQLite files
http://sqlitebrowser.org
SQLite is embedded in Python and a number of other languages
29
Text
http://sqlitebrowser.org/
30
Start Simple - A Single Table
CREATE TABLE Users(
name TEXT,
email TEXT
)
31
Start Simple - A Single Table
32
SQL Insert
The Insert statement inserts a row into a table:
INSERT INTO Users (name, email) VALUES ('Kristin', ‘
[email protected]')
33
SQL Delete
Deletes a row in a table based on a selection criteria:
• DELETE FROM Users WHERE email='[email protected]'
34
SQL Update
Allows the updating of a field with a where clause:
• UPDATE Users SET name='Charles' WHERE email=‘[email protected]'
35
Retrieving Records: Select
The select statement retrieves a group of records - you can
either retrieve all the records or a subset of the records with
a WHERE clause:
SELECT * FROM Users
SELECT * FROM Users WHERE email='
[email protected]'
36
Sorting with ORDER BY
You can add an ORDER BY clause to SELECT
statements to get the results sorted in ascending or
descending order:
SELECT * FROM Users ORDER BY email
SELECT * FROM Users ORDER BY name
37
SQL Summary
INSERT INTO Users (name, email) VALUES ('Kristin',
‘[email protected]')
UPDATE Users SET name="Charles" WHERE email='[email protected]'
SELECT * FROM Users
SELECT * FROM Users ORDER BY email
38
SQLite – Python
39
Error Handling With Exceptions
• Exceptions are used to deal with extraordinary errors (‘exceptional ones’).
• Typically these are fatal runtime errors (“crashes” program)
• Example: trying to open a non-existent file
• Basic structure of handling exceptions:
try:
Attempt something where exception error may happen
except <exception type>:
React to the error
else: # Not always needed (optional)
What to do if no error is encountered
finally: # Not always needed (optional)
The finally clause is optional. It is intended to define clean-up actions that must
be executed under all circumstances 40
SQLite in Python
Four things need to happen for Python to interact with SQLite
Import the sqlite module
import sqlite3
Connection to the database (or create one) with a given name
connection = sqlite3.connect(‘databasename.sql’)
Get a cursor to the database:
cursor = connection.cursor()
Execute queries on the cursor:
cursor.execute(‘SELECT * FROM .... ‘)
41
SQLite in Python
• Once a query has been executed on the cursor, some data might be
available, e.g. if you made a SELECT query
• cursor.fetchone() will return one record at a time.
• cursor.fetchall() will return all matching records at once in a Python list.
• You have to test if the result is None before using it.
• Don’t forget to call connection.commit() to commit the changes
42
SQLite in Python - Example
conn = sqlite3.connect(‘Payroll.db')
c = conn.cursor()
sql = '''
CREATE TABLE IF NOT EXISTS Employee (
id integer PRIMARY KEY,
name text,
salary real,
mobilephone integer
)
'''
c.execute(sql)
conn.commit()
conn.close()
43
SQLite in Python – Example (contd.)
def log(id, name, salary, mobilephone):
'''
logs data in the database.
id: number
name: string
salary: number, mobilephone: number
'''
data = (id, name, salary, mobilephone)
conn = sqlite3.connect(‘Payroll.db')
c = conn.cursor()
sql = 'INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)’ #? Works as a placeholder
c.execute(sql, data)
conn.commit()
conn.close()
44
Summary
• Database enable applications to store data in a persistent manner
• Designing a database requires identification of columns and attributes
• multiple tables in a single database are related using different types of
relationships
• SQL is a querying language that enable users to interact with databases
45
Next Session!
• Data structures:
• Tuples
• Lists
46
47