0% found this document useful (0 votes)
149 views42 pages

01 Introduction To SQLite

This document provides an introduction to using SQLite databases with Python. It discusses key database concepts like tables, records, and fields. It also explains common SQL statements like CREATE TABLE, SELECT, UPDATE, DELETE, and INSERT which are used to interact with and manipulate database tables. Examples are provided for each statement to demonstrate how to structure SQL queries to create tables, select data, update records, and insert new data into SQLite databases from Python.

Uploaded by

Zuhdija
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
149 views42 pages

01 Introduction To SQLite

This document provides an introduction to using SQLite databases with Python. It discusses key database concepts like tables, records, and fields. It also explains common SQL statements like CREATE TABLE, SELECT, UPDATE, DELETE, and INSERT which are used to interact with and manipulate database tables. Examples are provided for each statement to demonstrate how to structure SQL queries to create tables, select data, update records, and insert new data into SQLite databases from Python.

Uploaded by

Zuhdija
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 42

ComputerScienceUK Programming Guide – Python & SQLite

Introduction to SQLite

Programming Guides

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Prepare yourselves…
…there is a lot to take in

• We will first look at the SQL language in general terms – this language is
independent of any programming language.

• We will then look at how Python implements this language using its own module
called ‘SQLite3’.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Introduction
A database is a table, or a collection of tables that store data.

The software that operates on this data is called a database management system
(DBMS)….

….and all database management systems will need to be able to carry out the
following actions:

- Create a database
- Add data to the database
- Delete data from the database
- Edit the data
- Search the database for specific for data
www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Database Terminology
TABLE: A table is simply a collection of data that relates to a person or object (often referred to as an entity
(e.g. students))
RECORD: A collection of data about a single entity (e.g. a student)
FIELD: A unique piece of data about an entity (student surnames)
FIELD NAME: An identifier for the single piece of data (e.g. ‘surnames’).

Field Name Field

Table
Record

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Queries
A very common job carried out on a database is a query.

A query is where we search for data in our database. We ask the database
questions and it responds with answers. For example, we might ask our database
for all students who are 14 and the database will respond with a list of all
students that match the ‘age=14’ criteria.

When we write programs that have databases, SQL (structured query language)
is the language we use to create, update, delete and query our program’s
database.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SQL
The SQL language is made up of a selection of statements to carry out jobs on
databases.

There are quite a few but the basic / common statements are:

• CREATE TABLE – create a database table


• SELECT – selects data
• UPDATE – edits data
• DELETE – removes data
• INSERT INTO – inserts new data

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


CREATE-ing a Table
If we wanted to create the following empty table…

…we would use the following syntax:

Example: The first line of SQL creates a table


A B L E Student
s called ‘Students’.
T
CREATE xt,
t_ID te
(studen ,
me text
fi r s t _ n a
text,
The following lines, separated by
surname
group t
ext, commas specify the name of each
ber) column and the type of data it is to
age num
hold.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECT-ing Data
The SELECT statement is used to select particular data that we want to work on. We
could select the entire table or specific data based on certain criteria.

Using this example table…

…to select data we could use the following syntax:

Example: M students
Would
rs t_na m e F RO produce…
SELECT fi

This particular example will select all data in the


column called ‘first_name’.
www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECT-ing Data Examples
As already seen, the SQL in this first example will select
all data in the column called ‘first_name’.
The second example shows how you can select multiple
columns from a table.

1: 2:
Example ROM stud
ents Example dents
CT firs t_ na m e F
su rn a me FROM stu
S EL E ame,
S EL E CT first_n

Would Would
produce… produce…

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECT-ing Data Examples
If we want to select everything we can use the wildcard (*).

3:
Example
FRO M students
S EL E C T *

o d u ce
Would pr
t a b l e…
the entire

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The WHERE Clause
The “Where” clause is used with the ‘Select’ statement and is great if we want to drill
down and retrieve specific data which match a given criteria.

The SQL in this example selects all rows in the table


where the value in the field column matches ‘9AB’.

Example:
dents
FROM stu
SELECT * p=’9AB’
rou
WHERE g
od u ce…
Would pr

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The UPDATE Statement
The ‘update’ statement allows us to update / alter data that is already stored in the
database.

The WHERE statement sets the particular record to be updated.


If there is no value in the WHERE statement, then all the records will be updated.
The SQL in this example will update the table called students,
changing the surname to ‘Goodie’, but only in the row(s)
where the first name matches the value ‘Tess’.

Example
Would pr
:
U
od uceS PDATE students
ET surna
me = ‘Go
WHERE o
first_nam die’
e=’Tess’

Notice that Tess now has the surname ‘Goodie’.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The INSERT Statement
If we want to insert new data into our database we can use the INSERT INTO statement.

INSERT
Ex ample:
INTO stu
VALUES den
(‘009’, ‘J ts
im’, ‘Sm
ith’, ‘9AB
’, ‘14’)

Would pr
o d uce The SQL in this example will insert a new row
into the table called students, with the values
specified in the brackets. They will be entered
in the order in which they are provided.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The DELETE Statement
Unsurprisingly this statement is used to delete a record / records from a database.

Example
DELETE
:
FROM s
WHERE tud
first_nam ents
e=’Jim’

Would pr
o duceThe SQL in this example will delete the row(s)
in the table called students, where the value in
the field called ‘first_name’ matches ‘Jim’.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The LIKE Statement
The LIKE statement is used with a WHERE statement in order to find patterns within the
data in a column. For example it can be used along with a wildcard ‘%’ to find all names
that start with a particular letter.
Example
SE LECT *
:
FROM s
WHERE tu
first_nam dents
e LIKE ‘
T%’

Would pr
o duceThe SQL in this example will select all row(s)
in the table called students, where the value in
the field called ‘first_name’ starts with the
letter ‘t’.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The JOIN Statement
The JOIN statement is used to select records in two separate tables that both have the
same value.
Example
S ELE :
CT Or
FROM O ders.OrderNo, C
rd ustomers
JOIN Cu ers .Surname
stomers O
N Orders
.Custome
rID = Cu
stomers.C
ustom erID

Would pr
od uce

The SQL in this example will join the order


numbers with the corresponding customer
surnames.
www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The DROP Statement
We have already seen how the DELETE statement can be used to delete data in a table / database. What is
important to recognise is that when data is deleted, the actual structure of the table/database will remain.

The DROP statement however, is used to delete either a table or a database’s data along with the
table/database structures.

Example
:
DROP T
ABLE st
udents

Would
p r o d u ce
The SQL in this example will
remove the table ‘students’
from existence.
No more table!

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Introduction
Python provides the SQLite3 library to manipulate lightweight disk databases.

SQLite3 is great for creating and manipulating databases that are stored on a local disk
along with a program file. It comes with Python and is easy to work with.

MySQL is far more powerful and uses a server to store databases created so that they can
be accessed from anywhere (online) providing that there is a network connection.

But MySQL is less easy to work with (partly due to the need for a dedicated server) and
so in A-Level we will look at how we can use SQLite3 to create and manipulate
databases.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Importing the SQLite3 Library
Before we try to create or use a database, we first have to import the SQLite3 library.

We use the keyword import for this.

This is demonstrated below.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Connect
Now that the SQLite3 library is imported, we can connect to and use a database.

Similar to files, before we use a database we need to have a file handler in our program that
interacts with the physical database on a disk or in the RAM.

We use the connect() function, as defined in the SQLite3 library. This function will open a
connection to the SQLite database file.

The following code snippet will connect to a database called “new_db”. It will also create the
database file if it is not present.

If the database file is not located in the same folder as the program then we can write out its path.
For example:

*The argument for the function is the file path for the database; notice that we use double backslash ‘\\’ in our file path as single backslash
denotes an escape sequence.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The Cursor Object
In Python, the cursor object allows us to work with and manipulate databases.
To create a cursor object we call the cursor method on the connection object.
In our example, the connection object is new_db, we will create a new cursor called c.

Now that we have a connection to our database and a cursor object, we can execute SQL
statements to create our table and insert data into our tables. We will create a table called
“Students” with properties such as first name, surname, date of birth and form.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Creating and
Manipulating
Data

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Execute Statement

Once we have created our cursor object we can issue SQL commands to the database
using the EXECUTE statement.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Creating a Table
With our cursor object (c), we can use the execute command to execute some
SQL code.

This is an example of the code needed to create a table.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Create database ONLY if file doesn’t already exists
Usually, when you create a new database, you need to set up the file’s fields.
Because we want to do this only when the file doesn’t already exist, it is
sensible to do this in a ‘if not’ structure.

Notice that we need


to import the ‘os’
module to enable
us to do this.

Otherwise, every time we run our program we will be running the code which
was needed the first time the program was executed which was to create the
database – running this code if the database is already set up will cause data
loss.
www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Create database ONLY if file doesn’t already exists
Full example:

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Using the INSERT INTO statement to populate
the table.
Again, with our cursor object (c), we can use the execute command to execute some more
SQL code.

This is an example of the code needed to insert data into the different fields of the newly
created table.

Notice that we are using the version where we do not specify the field names as
we will be inserting information into all columns

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Using the INSERT INTO statement to populate the
table with variables and not pre-set string data.

The example code below shows how it is possible to enter the contents of variables into
the database table using ‘?’ placeholders.

The insert statement is set up like before but where string data was entered, we simply add
a ‘?’. Then, after the SQL statement, we add the variables which we want to add in the
same order and for each of the question marks.

Notice again that we are using the version where we do not specify the field names
as we will be inserting information into all columns

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Commit and Close
When we have finished ‘talking’ to the database we use the commit() statement to
save/commit the final transaction.

Finally, we must close the database.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The Database File
After executing this code, the database called new_db.db will be created in the specified location with
a table called “Students” and the record inserted.

The physical files are shown below. Note that this file is not readable by normal programs on the
computer, and therefore if we open this file we will only see symbols.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Tasks
45 minutes

• Create a Database file which has the following fields:


– First name
– Surname
– Age
– Favourite Takeaway Food
• Add to the table, 3 records.
• Alter the code so that:
– the database file is only created if the file has not yet been
made
– the user of the program can input the data (which is then
stored in variables) before it is inserted into the database.
www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Reading Data

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECT-ing Data
The SELECT statement is used to select particular data that we want to work on. We
could select the entire table or specific data based on certain criteria.

Using this example table…

…to select data we could use the following syntax:

Example: M students
Would
rs t_na m e F RO produce…
SELECT fi

This particular example will select all data in the


column called ‘first_name’.
www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECT-ing Data Examples
As already seen, the SQL in this first example will select
all data in the column called ‘first_name’.
The second example shows how you can select multiple
columns from a table.

1: 2:
Example ROM stud
ents Example dents
CT firs t_ na m e F
su rn a me FROM stu
S EL E ame,
S EL E CT first_n

Would Would
produce… produce…

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECT-ing Data Examples
If we want to select everything we can use the wildcard (*).

3:
Example
FRO M students
S EL E C T *

o d u ce
Would pr
t a b l e…
the entire

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


The WHERE Clause
The “Where” clause is used with the ‘Select’ statement and is great if we want to drill
down and retrieve specific data which match a given criteria.

The SQL in this example selects all rows in the table


where the value in the field column matches ‘9AB’.

Example:
dents
FROM stu
SELECT * p=’9AB’
rou
WHERE g
od u ce…
Would pr

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Reading from the Database
After we have selected the data that we wish to access, we use the FETCH commands to get the data
into our python program:

fetchall(...) Fetches all rows from the


result set
fetchmany(...) Fetches several rows from
the result set
fetchone(...) Fetches one row from the
result set

Example of reading and its result is on the next slide.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite

If the table of data was set up like this, we


could read the whole table by doing the
following:

We can use the SELECT *


(everything wildcard)…
…and then use the fetchall()
python function to put this data
into a list…which we can then Added to a list
manipulate or simply output
like shown here.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


SELECTING from the Database with the
WHERE clause.
If we wanted to read only the records which relate to a particular field, we could use the WHERE
clause in our SELECT statement first.

Here you can see how the


WHERE statement has
been used to select all data
where the form field
contains certain criteria
(8SCW). This data has then
been fetched into a list and
then outputted.

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Variations of the ‘Fetch’ function.
Once we have selected the data we wish to retrieve, we use the python ‘fetch’
function to lift data out of the database and into our program. There are different
variations that we could use and they are listed below:

Fetchall() can be used and assigned to a list so each row is


added to a different item of a list.

Fetchmany(40) can be used to fetch 40 of the records in the


db. This number can obviously be set to any number by the
programmer.

Fetchone() can be used to fetch only one record from the


database (the next record that the cursor is located at).

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Databases and SQLite


Improving the presentation:

t he r e a n
b u t i s
Better, w a y ? !
n be t t e r
e ve

www.computerscienceuk.com
ComputerScienceUK Programming Guide – Python & SQLite

Tasks
45 minutes

• Create a DBMS which records your movie


collection (name of movie, date, genre, rating
(look up IMDB)and that has a menu that offers
the user several options:
– View the whole database in a user friendly manner,
– Insert a new record,
– Search / Query records by field name.

www.computerscienceuk.com

You might also like