Database SQLite in Python
Database SQLite in Python
Database SQLite in Python
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/
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)
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
Database Administrator:
11
Database Model
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
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
15
Primary Key Rules
Best practices
Never use your logical key as the primary key
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)
24
Relationship Types: Many-to-Many (7/8)
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
• Insert data
• Delete data
28
SQLite Browser
SQLite is a very popular database - it is free and fast and small
http://sqlitebrowser.org
29
Text
http://sqlitebrowser.org/
30
Start Simple - A Single Table
31
Start Simple - A Single Table
32
SQL Insert
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
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]')
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:
import sqlite3
connection = sqlite3.connect(‘databasename.sql’)
cursor = connection.cursor()
• 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.)
44
Summary
45
Next Session!
• Data structures:
• Tuples
• Lists
46
47