Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

SQLiteUsingPython

Uploaded by

aboobackera839
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

SQLiteUsingPython

Uploaded by

aboobackera839
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

DEPARTMENT OF STATISTICS & OPERATIONS RESEARCH

AMU ALIGARH -202002 , U. P. (INDIA)

BIG DATA ANALYTICS (DSM 3002)


M.SC. III SEMESTER (DATA SCIENCE)
2023-24

DR ZAHID AHMED ANSARI


ACCESSING SQLITE USING PYTHON
3

Python SQLite Tutorial Using sqlite3

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


4

Python SQLite Database Connection


• How to Connect to SQLite Database in Python?
1. Import sqlite3 module: import sqlite3 statement imports the sqlite3 module in the program. Using the
classes and methods defined in the sqlite3 module we can communicate with the SQLite database.
2. Use the connect() method: Use the connect() method of the connector class with the database
name. To establish a connection to SQLite, you need to pass the database name you want to
connect. If you specify the database file name that already presents on the disk, it will connect to it.
But if your specified SQLite database file doesn’t exist, SQLite creates a new database for you. This
method returns the SQLite Connection Object if the connection is successful.
3. Use the cursor() method: Use the cursor() method of a connection class to create a cursor object to
execute SQLite command/queries from Python.
4. Use the execute() method: The execute() methods run the SQL query and return the result.
5. Extract result using fetchall(): Use cursor.fetchall() or fetchone() or fetchmany() to read query result.
6. Close cursor and connection objects: Use cursor.clsoe() and connection.clsoe() method to close the
cursor and SQLite connections after your work completes
7. Catch database exception if any that may occur during this connection process.
9/2/2024
5

WORKING OF PYTHON SQLITE3 MODULE

Dr. Zahid Ahmed Ansari 9/2/2024


6

CREATES AND CONNECTS TO THE NEW


DATABASE FILE SQLITE_PYTHON.DB
import sqlite3
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")

sqlite_select_Query = "select sqlite_version();"


cursor.execute(sqlite_select_Query)
record = cursor.fetchall()
print("SQLite Database Version is: ", record)
cursor.close()

except sqlite3.Error as error:


print("Error while connecting to sqlite", error)
finally:
if sqliteConnection: Output:
sqliteConnection.close() Database created and Successfully Connected to SQLite
print("The SQLite connection is closed") SQLite Database Version is: [('3.28.0',)]
The SQLite connection is closed 9/2/2024
7

IMPORTANT POINTS WHILE CONNECTING TO


SQLITE
• The connection object is not thread-safe. The sqlite3 module doesn’t allow sharing connections between
threads. If you still try to do so, you will get an exception at runtime.
• The connect() method accepts various arguments. In our example, we passed the database name argument
to connect.
• Using a connection object, we can create a cursor object which allows us to execute SQLite
command/queries through Python.
• We can create as many cursors as we want from a single connection object. Like a connection object, this
cursor object is also not thread-safe. The sqlite3 module doesn’t allow sharing cursors between threads. If
you still try to do so, you will get an exception at runtime.
• try-except-finally block: We placed all our code in this block to catch the SQLite database exceptions and
errors during this process.
• Using the Error class, we can handle any database error and exception that may occur while working with
SQLite from Python.
• The Error class helps us to understand the error in detail. It returns an error message and error code.
• It is always good practice to close the cursor and connection object once your work gets completed to avoid
database issues. 9/2/2024
8

Create SQLite Table from Python

• 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

Create SQLite Table from Python

import sqlite3 except sqlite3.Error as error:


try: print("Error while creating a sqlite table", error)
sqliteConnection = finally:
sqlite3.connect('SQLite_Python.db') if sqliteConnection:
sqlite_create_table_query = '''CREATE TABLE sqliteConnection.close()
SqliteDb_developers ( print("sqlite connection is closed")
id INTEGER PRIMARY KEY,
name TEXT NOT NULL, Output:
email text NOT NULL UNIQUE, Successfully Connected to SQLite
joining_date datetime, SQLite table created
salary REAL NOT NULL);''' sqlite connection is closed
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
cursor.execute(sqlite_create_table_query)
sqliteConnection.commit()
print("SQLite table created")
cursor.close()
9/2/2024
10

SQLITE DATATYPES AND CORRESPONDING PYTHON


TYPES

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


11

SQLITE DATATYPES AND CORRESPONDING PYTHON


TYPES

• 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 Types SQLite types


None NULL
int INTEGER
float REAL
str TEXT
bytes BLOB

Dr. Zahid Ahmed Ansari 9/2/2024


12

PERFORM SQLITE CRUD OPERATIONS FROM


PYTHON
• Most of the time, we need to manipulate the SQLite table’s data from Python.
• To perform these data manipulations, we execute DML queries, i.e., SQLite Insert, Update,
Delete operations from Python.
• We know the table and its column details, so let’s move to the crud operations.
1. Insert data into SQLite Table from Python: Learn how to execute INSERT command from
Python into Table.
2. Read SQLite Table’s data from Python:
3. Update data of SQLite table from Python
4. Delete data from SQLite table from Python

Dr. Zahid Ahmed Ansari 9/2/2024


13

How to Insert Into SQLite table from Python


1. Connect to SQLite from Python
2. Define a SQL Insert query: Next, prepare a SQL INSERT query to insert a row into a table. in the
insert query, we mention column names and their values to insert in a table.
3. For example, INSERT INTO mysql_table (column1, column2, …) VALUES (value1, value2, …);
4. Get Cursor Object from Connection: Next, use a connection.cursor() method to create a cursor
object. using cursor object we can execute SQL queries.
5. Execute the insert query using execute() method: The cursor.execute(query) method executes the
operation stored in the Insert query.
6. Commit your changes: After successfully executing an insert operation, make changes persistent
into a database using the commit() of a connection class.
7. Get the number of rows affected: After a successful insert operation, use a cursor.rowcount method
to get the number of rows affected. The count depends on how many rows you are Inserting.
8. Verify result using the SQL SELECT query: If required, execute SQLite select query from Python to
see the new changes.
9. Close the cursor object and database connection object: use cursor.clsoe() and connection.clsoe()
method to close the cursor and SQLite connections after your work completes.
14

INSERT DATA INTO SQLITEDB_DEVELOPERS TABLE


import sqlite3 except sqlite3.Error as error:
try: print("Failed to insert data into sqlite table", error)
sqliteConnection = sqlite3.connect('SQLite_Python.db') finally:
cursor = sqliteConnection.cursor() if sqliteConnection:
print("Successfully Connected to SQLite") sqliteConnection.close()
sqlite_insert_query = """INSERT INTO SqliteDb_developers print("The SQLite connection is closed")
(id, name, email, joining_date, salary)
VALUES Output:
(1,'James','james@pynative.com’, Successfully Connected to SQLite
'2019-03-17',8000)""" Record inserted successfully into table
count = cursor.execute(sqlite_insert_query) The SQLite connection is closed
sqliteConnection.commit()
print("Record inserted successfully into
SqliteDb_developers table ", cursor.rowcount)
cursor.close()
9/2/2024
15

USING PYTHON VARIABLES IN SQLITE INSERT


QUERY

• Sometimes we need to insert a Python variable value into a table’s column.


• This value can be anything, including integer, string, float, and DateTime.
• For example, in the registration form person enter his/her details. You can take
those values in Python variables and insert them into the SQLite table.
• We use a parameterized query to insert Python variables into the table.
• Using a parameterized query, we can pass python variables as a query parameter
in which placeholders (?)

Dr. Zahid Ahmed Ansari 9/2/2024


16

USING PYTHON VARIABLES IN SQLITE INSERT QUERY

import sqlite3 except sqlite3.Error as error:


def insertVaribleIntoTable(id, name, email, joinDate, salary): print("Failed to insert Python variable into sqlite table", error)
try: finally:
sqliteConnection = sqlite3.connect('SQLite_Python.db') if sqliteConnection:
cursor = sqliteConnection.cursor() sqliteConnection.close()
print("Connected to SQLite") print("The SQLite connection is closed")

sqlite_insert_with_param = """INSERT INTO SqliteDb_developers insertVaribleIntoTable(2, 'Joe', 'joe@pynative.com’,


(id, name, email, joining_date, salary) '2019-05-19', 9000)
VALUES (?, ?, ?, ?, ?);""" insertVaribleIntoTable(3, 'Ben', 'ben@pynative.com’,
'2019-02-23', 9500)
data_tuple = (id, name, email, joinDate, salary)
cursor.execute(sqlite_insert_with_param, data_tuple)
sqliteConnection.commit()
print("Python Variables inserted successfully into
SqliteDb_developers table")
cursor.close()
17

Insert Multiple Rows into SQLite Table Using the


Cursor’s executemany()

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


18

Insert Multiple Rows Using the Cursor’s executemany()

import sqlite3 except sqlite3.Error as error:


def insertMultipleRecords(recordList): print("Failed to insert multiple records into sqlite table",
try: error)
sqliteConnection = finally:
sqlite3.connect('SQLite_Python.db') if sqliteConnection:
sqliteConnection.close()
cursor = sqliteConnection.cursor()
print("The SQLite connection is closed")
print("Connected to SQLite")

recordsToInsert = [(4, 'Jos', 'jos@gmail.com', '2019-01-14', 9500),


sqlite_insert_query = """INSERT INTO
(5, 'Chris', 'chris@gmail.com', '2019-05-15', 7600),
SqliteDb_developers (6, 'Jonny', 'jonny@gmail.com', '2019-03-27', 8400)]
(id, name, email, joining_date, salary)
VALUES (?, ?, ?, ?, ?);""" insertMultipleRecords(recordsToInsert)

cursor.executemany(sqlite_insert_query, recordList) Output:


sqliteConnection.commit() Connected to SQLite
print("Total", cursor.rowcount, "Records inserted Total 3 Records inserted successfully into SqliteDb_developers
successfully into SqliteDb_developers table") table
sqliteConnection.commit() The SQLite connection is closed
9/2/2024
cursor.close()
19

Insert Multiple Rows Using the Cursor’s executemany()

• Let’s understand the above example

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


20

Steps to select rows from SQLite table


• Connect to SQLite from Python
• Define a SQLite SELECT Query: Next, prepare a SQLite SELECT query to fetch rows from a
table. You can select all or limited rows based on your requirement. For example, SELECT
column1, column2, columnN FROM table_name;
• Get Cursor Object from Connection: Next, use a connection.cursor() method to create a
cursor object. This method returns a cursor object. The Cursor object is required to execute
the query.
• Execute the SELECT query: Execute the select query using the cursor.execute(query)
method.
• Extract all rows from a result: After successfully executing a select operation, Use the
fetchall() method of a cursor object to get all rows from a query result. it returns a list of rows.
• Iterate each row: Iterate a row list using a for loop and access each row individually (Access
each row’s column data using a column name or index number.)
• Close the cursor object and database connection object: use cursor.clsoe() and
connection.clsoe() method to close the SQLite connection after your work completes. 9/2/2024
21

EXAMPLE TO READ ALL ROWS FROM SQLITE TABLE


import sqlite
def readSqliteTable():
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_select_query = """SELECT * from SqliteDb_developers"""
cursor.execute(sqlite_select_query)
records = cursor.fetchall()
print("Total rows are: ", len(records))
print("Printing each row")
for row in records:
print("Id: ", row[0])
print("Name: ", row[1])
print("Email: ", row[2])
print("JoiningDate: ", row[3])
print("Salary: ", row[4])
print("\n")
cursor.close() 9/2/2024
22

EXAMPLE TO READ ALL ROWS FROM SQLITE TABLE

except sqlite3.Error as error:


print("Failed to read data from sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")

readSqliteTable()

9/2/2024
23

EXAMPLE TO READ ALL ROWS FROM SQLITE TABLE


Connected to SQLite Id: 3
Total rows are: 6 Name: Ben
Printing each row
Email: ben@pynative.com

Id: 1 JoiningDate: 2019-02-23


Name: James Salary: 9500.0
Email: james@pynative.com
JoiningDate: 2019-03-17
Salary: 8000.0
Id: 4
Name: Jos
Id: 2
Name: Joe Email: jos@gmail.com
Email: joe@pynative.com JoiningDate: 2019-01-14
JoiningDate: 2019-05-19 Salary: 9500.0
Salary: 9000.0 9/2/2024
24

USE PYTHON VARIABLES AS PARAMETERS IN


QUERY

• 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.

• cursor.execute("SELECT salary FROM SqliteDb_developers WHERE id = "ID from


application"

Dr. Zahid Ahmed Ansari 9/2/2024


25

USE PYTHON VARIABLES AS PARAMETERS IN QUERY


import sqlite3 except sqlite3.Error as error:
def getDeveloperInfo(id): print("Failed to read data from sqlite table", error)
try: finally:
sqliteConnection = sqlite3.connect('SQLite_Python.db') if sqliteConnection:
cursor = sqliteConnection.cursor() sqliteConnection.close()
print("Connected to SQLite") print("The SQLite connection is closed")

sql_select_query = """select * from SqliteDb_developers getDeveloperInfo(2)


where id = ?"""
cursor.execute(sql_select_query, (id,))
Output:
records = cursor.fetchall()
Connected to SQLite
print("Printing ID ", id)
Printing ID 2
for row in records:
Name = Joe
print("Name = ", row[1])
Email = joe@pynative.com
print("Email = ", row[2])
JoiningDate = 2019-05-19
print("JoiningDate = ", row[3])
Salary = 9000.0
print("Salary = ", row[4])
The SQLite connection is closed
cursor.close()
26

SELECT LIMITED ROWS FROM SQLITE TABLE USING


CURSOR.FETCHMANY()

• 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

Dr. Zahid Ahmed Ansari 9/2/2024


27
SELECT LIMITED ROWS FROM SQLITE TABLE USING
CURSOR.FETCHMANY()
import sqlite3 except sqlite3.Error as error:
def readLimitedRows(rowSize): print("Failed to read data from sqlite table", error)
try: finally:
sqliteConnection = sqlite3.connect('SQLite_Python.db') if sqliteConnection:
cursor = sqliteConnection.cursor() sqliteConnection.close()
print("Connected to SQLite") print("The SQLite connection is closed")
sqlite_select_query = """SELECT * from SqliteDb_developers"""
cursor.execute(sqlite_select_query) readLimitedRows(2)
print("Reading ", rowSize, " rows")
records = cursor.fetchmany(rowSize)
print("Printing each row \n")
for row in records:
print("Id: ", row[0])
print("Name: ", row[1])
print("Email: ", row[2])
print("JoiningDate: ", row[3])
print("Salary: ", row[4])
print("\n")
cursor.close()
9/2/2024
28

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

The SQLite connection is closed 9/2/2024


29

SELECT A SINGLE ROW FROM SQLITE TABLE

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


30

SELECT A SINGLE ROW FROM SQLITE TABLE


import sqlite3 print("Failed to read single row from sqlite table", error)
def readSingleRow(developerId): finally:
try: if sqliteConnection:
sqliteConnection = sqliteConnection.close()
sqlite3.connect('SQLite_Python.db')
print("The SQLite connection is closed")
cursor = sqliteConnection.cursor()
readSingleRow(3)
print("Connected to SQLite")
sqlite_select_query = """SELECT * from
SqliteDb_developers where id = ?"""
cursor.execute(sqlite_select_query, (developerId,)) Output:
print("Reading single row \n") Connected to SQLite
record = cursor.fetchone() Reading single row
print("Id: ", record[0])
print("Name: ", record[1]) Id: 3
print("Email: ", record[2]) Name: Ben
print("JoiningDate: ", record[3]) Email: ben@pynative.com
print("Salary: ", record[4]) JoiningDate: 2019-02-23
cursor.close() Salary: 9500.0
except sqlite3.Error as error: The SQLite connection is closed 9/2/2024
31

UPDATE A SINGLE ROW OF SQLITE TABLE


To perform SQLite UPDATE query from Python, you need to follow these simple steps:
1. Connect to MySQL from Python
2. Prepare a SQL Update Query: Prepare an update statement query with data to update. Mention the
column name we want to update and its new value. For example, UPDATE table_name SET column1 =
value1, column2 = value2...., columnN = valueN WHERE [condition];
3. Execute the UPDATE query, using cursor.execute(): This method executes the operation stored in the
UPDATE query.
4. Commit your changes: After the successful execution of the SQLite update query, Don’t forget to commit
your changes to the database using connection.comit().
5. Extract the number of rows affected: After a successful update operation, use a cursor.rowcount method
to get the number of rows affected. The count depends on how many rows you are updating.
6. Verify result using the SQL SELECT query: Execute a SQLite select query from Python to see the new
changes
7. Close the cursor object and database connection object: use cursor.clsoe() and connection.clsoe()
method to close SQLite connections once the update operation completes.

9/2/2024
32

UPDATE A SINGLE ROW OF SQLITE TABLE


import sqlite3
def updateSqliteTable():
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sql_update_query = """Update SqliteDb_developers set salary = 10000 where id = 4"""
cursor.execute(sql_update_query)
sqliteConnection.commit()
print("Record Updated successfully ")
cursor.close()
except sqlite3.Error as error:
print("Failed to update sqlite table", error) Output:
finally: Connected to SQLite
if sqliteConnection: Record Updated successfully
sqliteConnection.close() The SQLite connection is closed
print("The SQLite connection is closed")
9/2/2024
updateSqliteTable()
33

USING PYTHON VARIABLES IN SQLITE UPDATE

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


34

USING PYTHON VARIABLES IN SQLITE UPDATE


import sqlite3
def updateSqliteTable(id, salary):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sql_update_query = """Update SqliteDb_developers set salary = ? where id = ?"""
data = (salary, id)
cursor.execute(sql_update_query, data)
sqliteConnection.commit()
print("Record Updated successfully")
cursor.close()
except sqlite3.Error as error:
print("Failed to update sqlite table", error) Output:
finally: Connected to SQLite
if sqliteConnection: Record Updated successfully
sqliteConnection.close() The SQLite connection is closed
print("The sqlite connection is closed") 9/2/2024
updateSqliteTable(3, 7500)
35

USING PYTHON VARIABLES IN SQLITE UPDATE

• Let’s understand the above program

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


36

UPDATE MULTIPLE ROWS USING CURSOR’S


EXECUTEMANY()

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


37

UPDATE MULTIPLE ROWS USING EXECUTEMANY()


import sqlite3
def updateMultipleRecords(recordList):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_update_query = """Update SqliteDb_developers set salary = ? where id = ?"""
cursor.executemany(sqlite_update_query, recordList)
sqliteConnection.commit()
print("Total", cursor.rowcount, "Records updated successfully")
sqliteConnection.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to update multiple records of sqlite table", error)
finally:
if sqliteConnection: Output:
sqliteConnection.close() Connected to SQLite
print("The SQLite connection is closed") Total 3 Records updated successfully
records_to_update = [(9700, 4), (7800, 5), (8400, 6)] The SQLite connection is closed
updateMultipleRecords(records_to_update)
38

UPDATE MULTIPLE ROWS USING


EXECUTEMANY()

• 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.

Dr. Zahid Ahmed Ansari 9/2/2024


39

UPDATE MULTIPLE COLUMNS OF SQLITE


TABLE

• We can also update multiple columns of an SQLite table in a single query.


Just prepare a parameterized query using a placeholder to update multiple
columns. Let see this with an example program.

Dr. Zahid Ahmed Ansari 9/2/2024


40

UPDATE MULTIPLE COLUMNS OF SQLITE TABLE


import sqlite3
def updateMultipleColumns(id, salary, email):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_update_query = """Update SqliteDb_developers set salary = ?, email = ? where id = ?"""
columnValues = (salary, email, id)
cursor.execute(sqlite_update_query, columnValues)
sqliteConnection.commit()
print("Multiple columns updated successfully")
sqliteConnection.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to update multiple columns of sqlite table", error)
finally: Output:
if sqliteConnection: Connected to SQLite
sqliteConnection.close() Multiple columns updated successfully
print("sqlite connection is closed") sqlite connection is closed
updateMultipleColumns(3, 6500, 'ben_stokes@gmail.com')
41

DELETE A SINGLE ROW FROM SQLITE TABLE


• Connect to SQLite from Python
• Define a SQL Delete Query: Next, prepare a SQL delete query to delete a row from a table. Delete query
contains the row to be deleted based on a condition placed in where clause of a query.
• For example, DELETE FROM MySQL_table WHERE id=10;
• Get Cursor Object from Connection
• Next, use a connection.cursor() method to create a cursor object. using cursor object we can execute SQL
queries.
• Execute the delete query using execute() method: The cursor.execute(query) method executes the operation
stored in the delete query.
• After a successful delete operation, the execute() method returns the number of rows affected.
• Commit your changes: After successfully executing a delete operation, make changes persistent into a
database using the commit() of a connection class.
• Get the number of rows affected: Use a cursor.rowcount method to get the number of rows affected. The
count depends on how many rows you are deleting.
• You can also execute SQLite select query from Python to verify the result.
• Close the cursor object and database connection object: use cursor.clsoe() and connection.clsoe() method
to close the cursor and SQLite connections after your work completes.
9/2/2024
42

DELETE A SINGLE ROW FROM SQLITE TABLE


import sqlite3
def deleteRecord():
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
# Deleting single record now
sql_delete_query = """DELETE from SqliteDb_developers where id = 6"""
cursor.execute(sql_delete_query)
sqliteConnection.commit()
print("Record deleted successfully ")
cursor.close()
except sqlite3.Error as error:
print("Failed to delete record from sqlite table", error)
Output:
finally:
Connected to SQLite
if sqliteConnection:
Record deleted successfully
sqliteConnection.close()
the sqlite connection is closed
print("the sqlite connection is closed")
deleteRecord()
43

USE PYTHON VARIABLE IN A QUERY TO


DELETE ROW FROM SQLITE TABLE
• Most of the time, we need to delete a row from an SQLite table where the id
passed at runtime. For example, when a user cancels his/her subscription, we
need to delete the entry from a table as per the user id. 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 delete runtime values and prevent SQL
injection concerns.

Dr. Zahid Ahmed Ansari 9/2/2024


44

USE VARIABLE IN A QUERY TO DELETE ROW


import sqlite3
def deleteSqliteRecord(id):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sql_update_query = """DELETE from SqliteDb_developers where id = ?"""
cursor.execute(sql_update_query, (id,))
sqliteConnection.commit()
print("Record deleted successfully")
cursor.close()
except sqlite3.Error as error:
print("Failed to delete reocord from a sqlite table", error)
finally:
Output:
if sqliteConnection:
Connected to SQLite
sqliteConnection.close()
Record deleted successfully
print("sqlite connection is closed")
the sqlite connection is closed
deleteSqliteRecord(5)
45

USE VARIABLE IN A QUERY TO DELETE ROW

• Let’s understand the above example

• We used the parameterized query to accept developer id at runtime using a


placeholder(?) for the id column
• Next, We then prepared data tuple by using Python variables.
• Next, we passed the SQL delete query and data tuple to a cursor.execute()
method.
• In the end, we made our changes permanent into the database using a
commit() method of a connection class.

Dr. Zahid Ahmed Ansari 9/2/2024


46

DELETE MULTIPLE ROWS FROM SQLITE TABLE

• In the above example, we have used execute() method of cursor object to


update a single record, but sometimes, we need to delete an N-number of
rows. For example, You want to delete employee data from the developer’s
table who left the organization.
• Instead of executing a delete query repeatedly to delete each record, you
can perform the bulk delete operation in a single query using the
cursor.executemany() method.
• The executemany(query, seq_param) method accepts two parameters a
SQL query and a list of records to delete.
• In this example, we are removing three rows.

Dr. Zahid Ahmed Ansari 9/2/2024


47

USE VARIABLE IN A QUERY TO DELETE ROW


import sqlite3
def deleteMultipleRecords(idList):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_update_query = """DELETE from SqliteDb_developers where id = ?"""

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

• Let’s understand the above example


• We prepared SQLite parameterized delete query with a single placeholder and then
created a list of Ids to remove in tuple format.
• Each element of a list is nothing but a tuple for each row. Each tuple contains the id
of a developer. Here we created three tuples, so we are deleting three rows.
• Next, we called a executemany() method to delete multiple rows from the SQLite
table.
• To get to know the number of records updated, we used a cursor.rowcount method.

Dr. Zahid Ahmed Ansari 9/2/2024


49

THANK YOU!

Dr. Zahid Ahmed Ansari 9/2/2024

You might also like