SQLiteUsingPython
SQLiteUsingPython
• This Python SQLite tutorial aims to demonstrate how to develop Python database
applications with the SQLite database.
• SQLite is a C-language library that implements a SQL database engine that is relatively
quick, serverless, and self-contained, high-reliable. SQLite is the most commonly used
database engine in the test environment (Refer to SQLite Home page).
• SQLite comes built-in with most computers and mobile devices, and browsers. Python’s
official sqlite3 module helps us to work with the SQLite database.
• Create a table statement is a DDL query. Let see how to execute it from Python.
• In this example, we are creating a SqliteDb_developers table inside the
SQLite_Python.db database.
• Steps for create a table in SQLite from Python:
1. Connect to SQLite using a sqlite3.connect().
2. Prepare a create table query.
3. Execute the query using a cursor.execute(query)
9/2/2024
9
• Before executing SQLite CRUD operations from Python, first understand SQLite data type and their
corresponding Python types, which will help us store and read data from the SQLite table.
• SQLite database engine has multiple storage classes to store values. Every value stored in an SQLite
database has one of the following storage classes or data types.
• SQLite DataTypes
• NULL: The value is a NULL value.
• INTEGER: To store the numeric value. The integer stored in 1, 2, 3, 4, 6, or 8 bytes depending on the
magnitude of the number.
• REAL: The value is a floating-point value, for example, 3.14 value of PI
• TEXT: The value is a text string, TEXT value stored using the UTF-8, UTF-16BE or UTF-16LE encoding.
• BLOB: The value is a blob of data, i.e., binary data. It is used to store images and files.
• The following Python types get converted to SQLite without any problem.
• So when you are modifying or reading from the SQLite table by performing CRUD
operations, remember this table.
• Python Insert multiple rows into SQLite table using the cursor’s executemany()
• In the above example, we have used execute() method of cursor object to insert a
single record. Still, sometimes we need to insert multiple rows into the table in a
single insert query.
• For example, You wanted to add all records from the CSV file into the SQLite table.
Instead of executing the INSERT query every time to add each record, you can
perform a bulk insert operation in a single query using a cursor’s executemany()
function.
• The executemany() method takes two arguments SQL query and records to update.
• After connecting to SQLite, We prepared a list of records to insert into the SQLite
table. Each entry in the list is nothing but a table tuple (row)
• SQL INSERT statement contains the parameterized query, which uses the
placeholder (?) for each column value.
• Next, Using cursor.executemany(sqlite_insert_query, recordList) , we inserted
multiple rows into the table.
• To get to know the number of records inserted, we used a cursor.rowcount method.
readSqliteTable()
9/2/2024
23
• We often need to pass a variable to SQLite select query in where clause to check some
condition.
• Let’s say the application wants to fetch person details by giving any id at runtime. To handle
such a requirement, we need to use a parameterized query.
• A parameterized query is a query in which placeholders (?) are used for parameters and the
parameter values supplied at execution time.
• In some circumstances, fetching all the data rows from a table is a time-
consuming task if a table contains thousands of rows.
• To fetch all rows, we have to use more resources, so we need more space
and processing time. To enhance performance, use the fetchmany(SIZE)
method of a cursor class to fetch fewer rows
OUTPUT
Connected to SQLite
Reading 2 rows
Printing each row
Id: 1
Name: James
Email: james@pynative.com
JoiningDate: 2019-03-17
Salary: 8000.0
Id: 2
Name: Joe
Email: joe@pynative.com
JoiningDate: 2019-05-19
Salary: 9000.0
• When you want to read only one row from the SQLite table, then you should
use fetchone() method of a cursor class.
• You can also use this method in situations when you know the query is going
to return only one row.
• The cursor.fetchone() method retrieves the next row from the result set.
9/2/2024
32
• Most of the time, we need to update a table with some runtime values. For example, when
users update their profile or any other details through a user interface, we need to update a
table with those new values.
• In such cases, It is always best practice to use a parameterized query.
• The parameterized query uses placeholders (?) inside SQL statements that contain input
from users. It helps us to update runtime values and prevent SQL injection concerns.
• We used two placeholders in the update query, one for the salary column
and the other is for the id column.
• Next, We prepared a data tuple by specifying two Python variables in
sequential order.
• Next, we passed the SQL update query and data tuple to the
cursor.execute() method. Remember variables order in the tuple is
sequential as per column placeholders order.
• In the above example, we have used execute() method of cursor object to update
a single record. But sometimes, we need to update multiple rows of the SQLite table.
For example, you want to increase the salary of developers by 20%.
• Instead of executing the UPDATE query every time to update each record, you can
perform bulk update operations in a single query using the cursor.executemany()
method.
• The executemany(query, seq_param) method accepts the following two
parameters
• SQL query
• list of records to be updated.
• Now, let see the example. In this example, we are updating three rows.
• We prepared the SQLite update query with two placeholders (“salary” and “Id”
column ) and a list of records to update in tuple format.
• Each element of a list is nothing but a tuple for each row. Each tuple contains two
values, i.e., salary and id of a developer.
• We passed SQLite update query and record list to executemany() as arguments.
• To get to know the number of records updated, we used a cursor.rowcount function.
• You can verify the result by selecting data from a SQLite table using Python.
• The parameterized query uses placeholders (?) inside SQL statements that
contain input from users. It helps us to delete runtime values and prevent SQL
injection concerns.
cursor.executemany(sqlite_update_query, idList)
sqliteConnection.commit()
print("Total", cursor.rowcount, "Records deleted successfully")
cursor.close()
except sqlite3.Error as error:
print("Failed to delete multiple records from sqlite table", error)
finally:
if sqliteConnection: Output:
sqliteConnection.close() Connected to SQLite
print("sqlite connection is closed") Total 2 Records deleted successfully
idsToDelete = [(4,), (3,)] sqlite connection is closed
deleteMultipleRecords(idsToDelete)
48
THANK YOU!