Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Starting out with Python

Fifth Edition, Global Edition

Chapter 14
Database Programming

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 1


Topics
• Database Management • Updating and Deleting
Systems Existing Rows
• Tables, Rows, and Columns • More About Primary Keys
• Opening and Closing a • Handling Database
Database Connection with Exceptions
SQLite
• CRUD Operations
• Creating and Deleting Tables
• Relational Data
• Adding Data to a Table
• Querying Data with the SQL
SELECT Statement

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 2


Database Management Systems (1 of 3)
• Storing data in traditional files has its limits
– well suited for applications that store only a small
amount of data
– not practical for applications that must store a large
amount of data
– simple operations become cumbersome and inefficient
as data increases

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 3


Database Management Systems (2 of 3)
• A database management system (DBMS) is software
that is specifically designed to work with large
amounts of data in an efficient and organized manner
– Data is stored using the database management system
– Applications written in Python or other languages
communicate with the DBMS rather than manipulate
the data directly
– DBMS carries out instructions and sends the results
back to the application

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 4


Database Management Systems (3 of 3)
The application The application uses
sends a command the result in its
Python Application
to the DBMS computation

The DBMS executes Database The DBMS sends the


the command on the Management result back to the
data System
application

Data

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 5


SQL
• SQL stands for structured query language
• A standard language for working with database
management systems
• Not used as a general programming language
• Consists of several key words, used to construct
statements
• SQL statements are strings passed from the
application to the DBMS using API method calls
• Serve as instructions for the DBMS to carry out
operations on its data

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 6


SQLite
• In this class we use the SQLite database
management system
• It is easy to use
• It is automatically installed with Python in a module
named sqlite3
• Use this import statement:

import sqlite3

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 7


Tables, Rows, and Columns (1 of 3)
• A database management system stores data in a
database
• A database is organized into one or more tables
• Each table holds a collection of related data,
organized into rows and columns
• A row is a complete set of data about a single item,
divided into columns
• Each column is an individual piece of data about the
item

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 8


Tables, Rows, and Columns (2 of 3)

Column Column Column Column

Row
Row
Row
Row
Row

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 9


Tables, Rows, and Columns (3 of 3)

Name Phone
Katie Allen 555-1234
This row contains data
Jill Ammons 555-5678
about one person:
Kevin Brown 555-9012
Name: Kevin Brown
Elisa Garcia 555-3456
Phone: 555-9012
Jeff Jenkins 555-7890
Leo Killian 555-1122
Marcia Potemkin 555-3344
Kelsey Rose 555-5566

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 10


Column Data Types

SQLite Data Type Description Corresponding Python Data


Type
NULL Unknown value None
INTEGER Integer number int
REAL Real number float
TEXT String str
BLOB Binary Large Object Can be any object

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 11


Primary Keys
• A primary key is a column that holds a unique value
for each row in a database table
• The primary key is used to identify a specific row
• Example:
– A table stores employee data, and one of the columns
holds employee ID numbers
– Because each employee’s ID number is unique, this
column can be used as the primary key

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 12


Identity Columns
• An identity column is a column that contains unique
values that are generated by the DBMS
• Identity columns typically contain integers that are
autoincremented
• When a table does not have a column that contains
unique values, an identity column can be created and
used as the primary key

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 13


Null Values
• If a column contains no data, it is said to be null
• Sometimes this is OK
• However, a primary key can never be null
• You can apply a constraint to a column to prevent it
from being null

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 14


Database Connections (1 of 2)
• Typical process of using an SQLite database:

Connect to the database


Get a cursor for the database
Perform operations on the database
Commit changes to the database
Close the connection to the database

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 15


Database Connections (2 of 2)
1 import sqlite3 The connect method returns a
2 Connection object for the
database.
3 def main():
4 conn = sqlite3.connect('contacts.db')
5 cur = conn.cursor() If the database does not
exist, it will be created.
6
7 # Insert code here to perform operations on the
database.
8
9 conn.commit() The commit method saves
10 conn.close() changes to the database.
11 The close method closes the
12 # Execute the main function. connection to the database.
14 if __name__ == '__main__':
15 main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 16


Passing SQL Statements to the DBMS
• To execute an SQL statement on an SQLite database:
– Construct a string that holds the SQL statement
– Pass the string to the Cursor object’s execute
method

cur.execute(SQLstring)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 17


Creating a Table (1 of 5)
• To add a table, use the SQL statement CREATE
TABLE
– General Format:
CREATE TABLE TableName (ColumnName1 DataType1,
ColumnName2 DataType2, etc...)

– Example:
CREATE TABLE Inventory (ItemName TEXT, Price REAL)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 18


Creating a Table (2 of 5)
• To designate a column as the primary key, use the
PRIMARY KEY constraint after the column's data type
– Example:

CREATE TABLE Inventory (ItemID INTEGER PRIMARY KEY,


ItemName TEXT,
Price REAL)

In SQLite, any column that is an INTEGER PRIMARY KEY


automatically becomes an autoincremented identity column.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 19


Creating a Table (3 of 5)
• The NOT NULL constraint specifies that a column
cannot be left empty:
– Example:

CREATE TABLE Inventory (ItemID INTEGER PRIMARY KEY NOT NULL,


ItemName TEXT,
Price REAL)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 20


Creating a Table (4 of 5)
1 import sqlite3
2
3 def main():
4 conn = sqlite3.connect('inventory.db')
5 cur = conn.cursor()
6 sql = '''CREATE TABLE Inventory (ItemID INTEGER PRIMARY KEY NOT NULL,
7 ItemName TEXT,
8 Price REAL)'''
9 cur.execute(sql)
10 conn.commit()
11 conn.close()
12
13 # Execute the main function.
14 if __name__ == '__main__':
15 main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 21


Creating a Table (5 of 5)
• Creating a table only if it does not already exist:
CREATE TABLE IF NOT EXIST Inventory (
ItemID INTEGER PRIMARY KEY NOT NULL,
ItemName TEXT,
Price REAL)

• Deleting a table:
DROP TABLE Inventory

DROP TABLE IF EXISTS Inventory

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 22


Adding Data to a Table (1 of 4)
• To add data to a table, use the INSERT statement
– General Format:

INSERT INTO TableName (ColumnName1, ColumnName2, etc...)


VALUES (Value1, Value2, etc...)

– Example:

INSERT INTO Inventory (ItemID, ItemName, Price)


VALUES (1, "Paint Brush", 8.99)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 23


Adding Data to a Table (2 of 4)
• If you omit the value of an INTEGER PRIMARY KEY,
SQLite will provide an auto-generated value for that
column
– Example (assume the Inventory table has an INTEGER PRIMARY
KEY column named ItemID):
INSERT INTO Inventory (ItemName, Price)
VALUES ("Paint Brush", 8.99)

– This statement will produce a new row with an auto-generated


integer value assigned to the ItemID column, “Paint Brush” will
be assigned to the ItemName column, and 8.99 will be assigned
to the Price column

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 24


Adding Data to a Table (3 of 4)
• Example
conn = sqlite3.connect('inventory.db')
cur = conn.cursor()
cur.execute('''INSERT INTO Inventory (ItemName, Price)
VALUES ("Screwdriver", 4.99)''')
cur.execute('''INSERT INTO Inventory (ItemName, Price)
VALUES ("Hammer", 12.99)''')
cur.execute('''INSERT INTO Inventory (ItemName, Price)
VALUES ("Vice Grips", 14.99)''')
conn.commit()
conn.close()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 25


Adding Data to a Table (4 of 4)
• Inserting multiple rows with one INSERT statement:

cur.execute('''INSERT INTO Inventory (ItemName, Price)


VALUES ("Screwdriver", 4.99),
("Hammer", 12.99),
("Vice Grips", 14.99)''')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 26


Inserting the Value of a Variable
• You can insert the value of a variable into an SQL
statement by using question-mark placeholders:

item_name = "Wrench"
price = 16.99
cur.execute('''INSERT INTO Inventory (ItemName, Price)
VALUES (?, ?)''',
(item_name, price))

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 27


The SELECT Statement (1 of 5)
• The SELECT statement is used to retrieve specified
rows from a table
– General format:

SELECT Columns FROM Table

– Columns is one or more column names


– Table is a table name

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 28


The SELECT Statement (2 of 5)
• Example 1: SELECT Description FROM Products

– Retrieves the Description column from every row in the


Products table

• Example 2: SELECT Description, Price FROM Products


– Multiple column names are separated with a comma
– Retrieves the Description and Price columns from every row
in the Products table

• Example 3: SELECT * FROM Products


– The * character can be used to retrieve all columns in the table

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 29


The SELECT Statement (3 of 5)
– In Python, using the SELECT statement with SQLite is
a two-step process:
 Execute the SELECT statement
– Pass the SELECT statement as a string to the Cursor object’s
execute method.
– The DBMS retrieves the results of the SELECT statement, but it
does not return those results to your program
 Fetch the results
– Call either the fetchall method or the fetchone method to
fetch the results
– Both of these are Cursor object methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 30


The SELECT Statement (4 of 5)
• Example (using fetchall)
– The fetchall method returns a list containing all the rows
that result from a SELECT statement

conn = sqlite3.connect('chocolate.db')
cur = conn.cursor()

cur.execute('SELECT Description, RetailPrice FROM Products')


results = cur.fetchall()

for row in results:


print(f'{row[0]:30} {row[1]:5}')

conn.close()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 31


The SELECT Statement (5 of 5)
• Example (using fetchone):
– The fetchone method returns only one row each time
it is called, as a tuple

conn = sqlite3.connect('chocolate.db')
cur = conn.cursor()
cur.execute('SELECT Description, RetailPrice FROM Products')
row = cur.fetchone()

while (row != None):


print(f'{row[0]:30} {row[1]:5}')
row = cur.fetchone()

conn.close()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 32


Specifying Search Criteria with the
WHERE Clause (1 of 6)
• The WHERE clause can be used with the SELECT
statement to specify search criteria
• When you use the WHERE clause, only the rows that
meet the search criteria will be returned in the result
set
– General format:
SELECT Columns FROM Table WHERE Criteria
– Criteria is a conditional expression

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 33


Specifying Search Criteria with the
WHERE Clause (2 of 6)
• Example:
SELECT * FROM Products WHERE RetailPrice > 10.00

– The first part of the statement, SELECT * FROM


Products, specifies that we want every column

– The WHERE clause specifies that we want only the rows in


which the RetailPrice column is greater than 10.00

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 34


Specifying Search Criteria with the
WHERE Clause (3 of 6)
• Example:
SELECT * FROM Products WHERE UnitsOnHand < 100

– The first part of the statement, SELECT * FROM


Products, specifies that we want every column
– The WHERE clause specifies that we want only the rows in
which the UnitsOnHand column is less than 100

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 35


Specifying Search Criteria with the
WHERE Clause (4 of 6)
• SQL Relational Operators

Operator Meaning
> Greater-Than
< Less-Than
>= Greater-Than or Equal-To
<= Less-Than or Equal-To
== Equal-To
= Equal-To
!= Not Equal-To
<> Not Equal-To

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 36


Specifying Search Criteria with the
WHERE Clause (5 of 6)
• SQL Logical Operators: AND, OR, NOT
SELECT * FROM Products
WHERE UnitCost > 3.00 AND UnitsOnHand < 100

SELECT * FROM Products


WHERE RetailPrice > 10.00 OR UnitsOnHand < 50

SELECT * FROM Products


WHERE NOT RetailPrice > 5.00

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 14 - 37

You might also like