Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 29eed14

Browse files
committed
Added databases and example code to support the lecture notes.
1 parent 62c4e0b commit 29eed14

15 files changed

+401
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,7 @@ venv.bak/
102102

103103
# mypy
104104
.mypy_cache/
105+
106+
# Exercise files - update when the course starts!
107+
IndEx1_STU_NUM.py
108+
IndEx1_STU_NUM.sql

IndEx1_STU_NUM.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
Provide Python code to create a SQLite database.
3+
Your solution may make use of either Python with sqlite3 OR Python with sqlalchemy.
4+
The structure of the database must be as follows:
5+
6+
Database name: Blog
7+
8+
Table names: Blogger, Post
9+
10+
Columns for Blogger table: blogger_id (integer, Foreign Key), username (text), email (text)
11+
12+
Columns for Post table: post_id (integer, Primary Key), title (text), post (text), blogger_id (integer, Foreign Key)
13+
14+
Add the following records to each table:
15+
[Blogger]
16+
1, weatherman, [email protected]
17+
2, gourmand123, [email protected]
18+
[Post]
19+
1, Weather, Today the weather is fine., 1
20+
2, Lunch, Fish and chips with ice-cream., 2
21+
3, Dinner, Green thai-curry for main with mango sticky rice for dessert., 2
22+
"""
23+

IndEx1_STU_NUM.sql

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Write queries to answer the following questions
3+
Save your work to this .sql file
4+
Right click on the file name in the Project pane and select Refactor > Rename, and replace STU_NUM with your student number.
5+
*/
6+
7+
--1. Which employees have 'IT' in their job title? (list their EmployeeId, FirstName, LastName and Title)
8+
SELECT EmployeeId, FirstName, LastName, Title FROM Employee WHERE Title LIKE "IT%";
9+
10+
--2. List the names of all Artists and the titles of their albums
11+
SELECT Artist.Name, Album.title FROM Artist JOIN Album ON Artist.ArtistId = Album.ArtistId ORDER BY Artist.Name;
12+
13+
--3. Which track is features on the greatest number of times in playlists and how many times is it included? (display Trac
14+
SELECT Track.Name, COUNT(PlaylistTrack.TrackId) FROM Track JOIN PlaylistTrack ON Track.TrackId = PlaylistTrack.TrackId LIMIT 5;
15+
16+
--4. Provide a list of the number of tracks by each artist
17+
18+
19+
--5. How much money has been invoiced for the artist Deep Purple? (display each line item from the invoices and the total amount)
20+
SELECT Artist.Name, SUM(InvoiceLine.UnitPrice*InvoiceLine.Quantity) FROM Artist
21+
JOIN Album on Artist.ArtistId = Album.ArtistId
22+
JOIN Track on Album.AlbumId = Track.AlbumId
23+
JOIN InvoiceLine on Track.TrackId = InvoiceLine.TrackId
24+
WHERE Artist.Name LIKE "Deep Purple";
25+
26+
UPDATE InvoiceLine SET Quantity=2 WHERE InvoiceLineId=96;
27+
UPDATE InvoiceLine SET Quantity=3 WHERE InvoiceLineId=129;
28+
UPDATE InvoiceLine SET Quantity=4 WHERE InvoiceLineId=130;
29+
30+
SELECT Artist.Name, InvoiceLine.InvoiceLineId, InvoiceLine.UnitPrice, InvoiceLine.Quantity FROM Artist
31+
JOIN Album on Artist.ArtistId = Album.ArtistId
32+
JOIN Track on Album.AlbumId = Track.AlbumId
33+
JOIN InvoiceLine on Track.TrackId = InvoiceLine.TrackId
34+
WHERE Artist.Name LIKE "Deep Purple";
35+
36+
/*
37+
Provide SQL to create a SQLite database with the following:
38+
Database name: Blog
39+
Table names: Blogger, Post
40+
Columns for Blogger table: blogger_id (integer, Foreign Key), username (text), email (text)
41+
Columns for Post table: post_id (integer, Primary Key), title (text), post (text), blogger_id (integer, Foreign Key)
42+
Add the following records to each table:
43+
[Blogger]
44+
1, weatherman, [email protected]
45+
2, gourmand123, [email protected]
46+
[Post]
47+
1, Weather, Today the weather is fine., 1
48+
2, Lunch, Fish and chips with ice-cream., 2
49+
3, Dinner, Green thai-curry for main with mango sticky rice for dessert., 2
50+
*/
51+

chinook.sqlite

1.02 MB
Binary file not shown.

chinook_queries.sql

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
--Provide a query showing Customers (just their full names, customer ID and country) who are not in the US.
2+
3+
4+
--Provide a query only showing the Customers from Brazil.
5+
6+
7+
/* Provide a query showing the Invoices of customers who are from Brazil.
8+
Show the customer's full name, Invoice ID, Date of the invoice and billing country.*/
9+
10+

chinook_queries_solutions.sql

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
--Provide a query showing Customers (just their full names, customer ID and country) who are not in the US.
2+
SELECT FirstName, LastName, CustomerId, Country
3+
from Customer
4+
WHERE Country NOT IN ("USA");
5+
6+
--Provide a query only showing the Customers from Brazil.
7+
SELECT FirstName, LastName
8+
FROM Customer
9+
WHERE Country LIKE "Brazil";
10+
11+
/* Provide a query showing the Invoices of customers who are from Brazil.
12+
Show the customer's full name, Invoice ID, Date of the invoice and billing country.*/
13+
SELECT InvoiceId, InvoiceDate, BillingCountry, FirstName, LastName
14+
FROM Customer
15+
JOIN Invoice ON Customer.CustomerId = Invoice.CustomerId
16+
WHERE Country LIKE "Brazil";

create_db_mysql.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import mysql.connector
2+
from mysql.connector import errorcode
3+
4+
DB_NAME = 'address_mysql'
5+
6+
# 1. Create the connection object (replace with your username and password for mysql)
7+
conn = mysql.connector.connect(
8+
host="localhost",
9+
user="comp0034",
10+
passwd="c0mpoo34",
11+
port=8889
12+
)
13+
14+
# 2. Create the cursor object
15+
c = conn.cursor()
16+
17+
# 3. Create the database and the use it
18+
c.execute("CREATE DATABASE IF NOT EXISTS address_mysql DEFAULT CHARACTER SET 'utf8'")
19+
c.execute("USE address_mysql")
20+
21+
# 4. Create the tables
22+
sql = '''CREATE TABLE `person` (
23+
`person_id` int NOT NULL AUTO_INCREMENT,
24+
`first_name` varchar(14) NOT NULL,
25+
`last_name` varchar(16) NOT NULL,
26+
PRIMARY KEY (`person_id`)
27+
) ENGINE=InnoDB'''
28+
c.execute(sql)
29+
30+
sql = '''CREATE TABLE `address` (
31+
`address_id` int NOT NULL AUTO_INCREMENT,
32+
`street_number` varchar(6) NOT NULL,
33+
`street_name` varchar(120) NOT NULL,
34+
`postcode` varchar(10) NOT NULL,
35+
`person_id` int NOT NULL,
36+
PRIMARY KEY (`address_id`),
37+
FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
38+
) ENGINE=InnoDB'''
39+
c.execute(sql)
40+
41+
# 4. Insert muliple rows into person
42+
values = [('David', 'Coverdale'),
43+
('Robert', 'Plant'),
44+
('Joe', 'Elliott')]
45+
sql = ("INSERT INTO person (first_name, last_name) VALUES (%s, %s)")
46+
c.executemany(sql, values)
47+
48+
# 5. Insert single row into address (for the last person entered)
49+
sql = "INSERT INTO address (street_number, street_name, postcode, person_id) VALUES (%s, %s, %s, %s)"
50+
values = (12, 'My Road', 'SE1 9PZ', c.lastrowid)
51+
c.execute(sql, values)
52+
53+
# 6. Insert address for a specific person (first select the id of the person and then insert the new address record)
54+
sql = '''INSERT INTO address (street_number, street_name, postcode, person_id) VALUES (%s, %s, %s,
55+
(SELECT person_id FROM person WHERE last_name LIKE "Plant"))'''
56+
values = (134, 'The Street', 'EN7 3RT')
57+
c.execute(sql, values)
58+
59+
# 7. Commit the changes
60+
conn.commit()
61+
62+
# 8. Close the cursor and the connection
63+
c.close()
64+
conn.close()

create_db_sqlalchemy.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
from sqlalchemy import Column, ForeignKey, Integer, String
2+
from sqlalchemy.ext.declarative import declarative_base
3+
from sqlalchemy.orm import relationship, sessionmaker
4+
from sqlalchemy import create_engine
5+
6+
# 1. Create an engine that stores data in a address_alchemy.db file in the local directory
7+
# The engine establishes a DBAPI connection to the database when a method like execute() or connect() is called
8+
engine = create_engine('sqlite:///address_sqlalchemy.db')
9+
10+
# 2. Describe the model (i.e. the database tables and the classesmapped to those)
11+
12+
# Create the declarative base class. This stores a catlog of classes and mapped tables using the Declarative system
13+
Base = declarative_base()
14+
15+
# Define the classes and tables
16+
class Person(Base):
17+
__tablename__ = 'person'
18+
person_id = Column(Integer, primary_key=True)
19+
first_name = Column(String(250), nullable=False)
20+
last_name = Column(String(250), nullable=False)
21+
address = relationship("Address")
22+
23+
def __repr__(self):
24+
return "<Person(id='%s', first_name='%s', last name='%s')>" % (self.person_id, self.first_name, self.last_name)
25+
26+
27+
class Address(Base):
28+
__tablename__ = 'address'
29+
address_id = Column(Integer, primary_key=True)
30+
street_name = Column(String(120))
31+
street_number = Column(String(6))
32+
post_code = Column(String(10))
33+
person_id = Column(Integer, ForeignKey('person.person_id'))
34+
35+
def __repr__(self):
36+
return "<Address('%s', '%s', '%s)>" % (
37+
self.street_number, self.street_name, self.post_code)
38+
39+
40+
# 3. Create all tables
41+
Base.metadata.create_all(engine)
42+
43+
# 4. Create a session object to allow us to interact with the database
44+
# Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine
45+
# object created earlier.
46+
Session = sessionmaker(bind=engine)
47+
session = Session()
48+
49+
# 5. Create people objects then add to the database using the session object
50+
p1 = Person(first_name='R2', last_name='D2')
51+
session.add(p1)
52+
53+
session.add_all([
54+
Person(first_name='Metal', last_name='Mickey'),
55+
Person(first_name='Marvin', last_name='Paranoid-Android'),
56+
Person(first_name='K', last_name='9')]
57+
)
58+
59+
# 4. Create address objects and add to the database
60+
# Add a person and their address
61+
et = Person(first_name='E.', last_name='T.')
62+
# Address has to be a list even if there is only one address
63+
et.address = [Address(street_number='1A', street_name='Brodo Asogi', post_code='')]
64+
session.add(et)
65+
66+
# Add an address for an existing person
67+
p2 = session.query(Person).filter_by(first_name='Metal').first()
68+
p2.address = [Address(street_number='34', street_name='Wilberforce Street', post_code='B4 7ET')]
69+
70+
# 5. Commit the changes to the database
71+
session.commit()
72+
73+
# 6. Close the session
74+
session.close()

create_db_sqlite.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import sqlite3
2+
3+
# Step 1: Create a connection object that represents the database
4+
conn = sqlite3.connect('address_sqlite.db')
5+
6+
# Step 2: Create a cursor object
7+
c = conn.cursor()
8+
9+
# Step 3: Create the person and address tables
10+
c.execute('''
11+
CREATE TABLE person
12+
(person_id INTEGER PRIMARY KEY,
13+
first_name text NOT NULL,
14+
last_name text NOT NULL)
15+
''')
16+
17+
c.execute('''
18+
CREATE TABLE address
19+
(address_id INTEGER PRIMARY KEY,
20+
street_number text,
21+
street_name text,
22+
postcode text NOT NULL,
23+
person_id INTEGER NOT NULL,
24+
FOREIGN KEY(person_id) REFERENCES person(person_id))
25+
''')
26+
27+
# Insert data for a person using values from variables
28+
# You could use: c.execute("INSERT INTO person VALUES('Jo', 'Bloggs')")
29+
sql = "INSERT INTO person (first_name, last_name) VALUES (?, ?)"
30+
values = ('Jo', 'Bloggs')
31+
c.execute(sql, values)
32+
33+
# Insert the address for the person
34+
# If you know the rowid you can use: c.execute("INSERT INTO address VALUES(1, 'My Road', 'SE1 9PZ', 1)")
35+
# Since we just inserted Jo this was the last insert so we can get the id of the last inserted row using c.lastrowid:
36+
sql = "INSERT INTO address ('street_number', street_name, postcode, person_id) VALUES (?, ?, ?, ?)"
37+
values = (12, 'My Road', 'SE1 9PZ', c.lastrowid)
38+
c.execute(sql, values)
39+
40+
# Insert multiple rows cursor.executemany()
41+
sql = "INSERT INTO person (first_name, last_name) VALUES (?, ?)"
42+
values = [('David', 'Coverdale'),
43+
('Robert', 'Plant'),
44+
('Joe', 'Elliott')]
45+
c.executemany(sql, values)
46+
47+
# Step 5: Save (commit) the changes
48+
conn.commit()
49+
50+
# Step 6 (optional): Close the connection if you are done with it
51+
# Be sure any changes have been committed or they will be lost.
52+
conn.close()

requirements.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
mysql-connector-python==8.0.17
2+
protobuf==3.9.0
3+
six==1.12.0
4+
SQLAlchemy==1.3.5

0 commit comments

Comments
 (0)