SQLite3 and Python
July 21, 2023 · 5 minute read
Introduction
sqlite3
. This module is a native Python module that allows us to connect to, and manage databases.
Step One: Establishing a Connection to the SQLite Database
connect()
method from the sqlite3
module. When using this method it attempts to connect to a databse in the directory where your program resides. Furthermore, if the connect method cannot find the database file, it will create a new database with the name you specified.
import sqlite3
connection = sqlite3.connect("testdb.db")
cursor = connection.cursor()
close()
as well as commit()
before closing to avoid losing changes.
Step Two: Adding Data to the database
CREATE TABLE
to create a table and, INSERT INTO
to add values to a table. Some examples can be seen below.
Syntax for Creating a Table
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
cursor = connection.cursor()
cursor.execute("CREATE TABLE TACOBELLMENU (ItemName varchar(255), ItemID int, Price float)")
Syntax for Adding Data
INSERT INTO
or UPDATE
statements, it's important to remember to use the commit()
method to save changes to your database.
INSERT INTO
statement, then the values correspond to the index of the columns. For example the first parameter will be applied to the first column and so on.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
cursor = connection.cursor()
cursor.execute("INSERT INTO TACOBELLMENU ('Burrito', 32, 7.92)")
connection.commit()
connection.close()
sqlite3
the question mark ?
is used as a placeholder. A tuple is then passed into the method which inserts the data using the variables.
cursor = connection.cursor()
name = "Chalupa"
itemID = 87
price = 3.872
cursor.execute("INSERT INTO TACOBELLMENU VALUES(?, ?, ?)", name, itemID, price)
connection.commit()
connection.close()
cursor = connection.cursor()
data = [{"name": "Chalupa", "itemID": 87, "price": 3.87},
{"name": "Cheesy Burrito", "itemID": 17, "price": 7.87},
{"name": "Refried Beans", "itemID": 89, "price": 10.11}]
cursor.execute("INSERT INTO TACOBELLMENU VALUES(:name, :itemID, :price)", data)
connection.commit()
connection.close()
Step Three: Reading Data from the Database
sqlite3
is straightforward and can be done by constructing a SELECT
statement in SQL. We can do this by using the execute()
method along with the appropriate SQL query. Once complete, you can either use fetchone()
or fetchall()
to access the data.
cursor = connection.cursor()
data = cursor.execute("SELECT * FROM TACOBELLMENU").fetchall()
for row in data:
print(row)
connection.close()
sqlite3
is a robust, native Python module that provides a lightweight and self-contained interface for working with databases. Key features of this module include connecting to the database, executing and fetching SQL statements and results, transaction methods such as commit, as well as parameter binding to prevent SQL injection vulnerabilities.