Python SQLite Tutorial - The Ultimate Guide
Python SQLite Tutorial - The Ultimate Guide
towardsdatascience.com/python-sqlite-tutorial-the-ultimate-guide-fdcb8d7a4f30
29 aprile 2020
Let’s learn all you need to get started with SQLite3 in Python! Source: Nik Piepenbreier
SQL and Python have quickly become quintessential skills for anyone taking on serious
data analysis! This Python SQLite tutorial is the only guide you need to get up and
running with SQLite in Python. In this post, we’ll cover off:
1/12
SQLite3 (what we’ll just call SQLite) is part of the standard Python 3 package, so you
won’t need to install anything. If you’re not running Python 3, check out this link to get
started.
If you’re looking to get started with SQL, check out my full Beginner’s SQL Tutorial,
which includes a free downloadable PDF and other freebies.
From this list, you may notice a number of missing data types such as dates.
Unfortunately, when using SQLite, you’re restricted to these data types.
2/12
Ready? Let’s get started! Source: Nik Piepenbreier
Let’s start off the tutorial by loading in the library. We can do this by using the following
command:
import sqlite3
Let’s first create a .db file, as this is a very standard way of actually maintaining a SQLite
database. We’ll represent the connection using a variable named conn. We’ll create a file
3/12
called orders.db.
conn = sqlite3.connect('orders.db')
With this line of code, we’ve created a new connection object, as well as a new file called
orders.db in the directory in which you’re working. If you wanted to specify a specific
directory, you could write:
conn = sqlite3.connect(r'PATH-TO-YOUR-DIRECTORY/orders.db')
If the file already exists, the connect function will simply connect to that file.
Note: Notice that we included the letter “r” before the string that contains this path.
This lets Python know that we’re working with a raw string, meaning that the “/” won’t
be used to escape characters. You can learn more about raw strings by checking out this
link.
The connect function creates a connection to the SQLite database and returns an object
to represent it.
In-Memory Databases
Another way of generating databases using SQLite in Python is to create them in
memory. This is a great way to generate databases that can be used for testing
purposes, as they exist only in RAM.
conn = sqlite3.connect(:memory:)
However, for the purposes of this tutorial, and for most use cases you’ll run into, you’ll
use the method we described earlier.
cur = conn.cursor()
4/12
Cursors are critical to SQLite3 in Python. Source: Nik Piepenbreier
Now that we have a cursor object, we can use it to run SQL queries in the following
style:
cur.execute("YOUR-SQL-QUERY-HERE;")
Notice that we wrapped our SQL query in quotes — this is important. It doesn’t matter if
we use single, double, or triple quotes. For longer queries, it’s often best to use triple
quotes, as they allow us to write multi-line queries.
cur.execute("""CREATE
TABLE IF NOT EXISTS
users(
userid INT PRIMARY
KEY,
fname TEXT,
lname TEXT,
gender TEXT);
""") A quick reminder of what our database looks like. Source: Nik
conn.commit() Piepenbreier
5/12
In the code above, we’re doing a number of things:
1. Using the execute function on the cursor object to execute a SQL query
2. Using SQL to generate a table called users
3. The IF NOT EXISTS will help us when reconnecting to the database. The query
will allow us to check if the table exists, and if it does, nothing is changed.
4. We create four columns: userid, fname, lname, and gender. userid is assigned to
be the primary key.
5. We committed the changes by using the commit function on the connection
object.
To create our other table, we can follow a similar pattern and write the following
commands:
After executing these two scripts, your database will have two tables. We’re now ready
to begin adding in data!
6/12
Let’s take a look at how to add data with SQLite in Python to the database we just
created. Similar to the table generation query, the query to add data uses the cursor
object to execute the query.
Often, when we’re working within Python, we’ll have variables that hold values for us.
For example, we may have a tuple that contains that information about a user which
might look like this:
If we wanted to load this data into our database, we would use a different convention:
What we did here was replace all the values with question marks and add an additional
parameter that contains the values we’re hoping to add.
It’s important to note here that the SQLite expects the values to be in tuple-format.
However, the variable can contain a list, as long as the list items are tuples. For
example, we could add more users using the variable:
In this case, instead of using the execute function, we’ll want to use the executemany
function:
If we had used the execute function on the cursor object here, the function would have
assumed we were passing two items into the table directly (the two tuples), rather than
two sets of four items each! Thankfully, the function would have failed in this instance,
but be careful about which function you use!
7/12
If you’re following along, load these data files in too! Source: Nik Piepenbreier
8/12
Using fetchone() in SQLite with Python
Let’s begin by using the fetchone() function. We create a variable one_result to pull only
result
This returns:
[(1, 'Nik', 'Piepenbreier', 'male'), (2, 'Lois', 'Lane', 'Female'), (3, 'Peter', 'Parker', 'Male')]
9/12
Let’s learn how to delete data as well! Source: Nik Piepenbreier
Now, we’ll take a look at how to delete data using SQLite in Python. We can accomplish
this using a similar structure to above. Say we wanted to delete any user with the last
name ‘Parker’, we could write:
This prints out an empty list, confirming that the record has been deleted.
Similarly, you could apply some other SQL tricks. For a complete introduction to SQL,
check out my complete beginner’s guide here.
Thanks so much for taking the time! You’re really, really awesome! Source: Nik Piepenbreier
Written by
Nik Piepenbreier
11/12
Founder of datagy.io || author of introduction to python for data science
bit.ly/3aErgNu || my YouTube channel https://bit.ly/2AptX91 || lover of puns
Discover Medium
Welcome to a place where words matter. On Medium, smart voices and original ideas
take center stage - with no ads in sight. Watch
Become a member
Get unlimited access to the best stories on Medium — and support writers while you’re
at it. Just $5/month. Upgrade
12/12