Python Delete Data in SQLite Database
In this tutorial, we’re going to learn how to write a Python program to delete a data record from SQLite data table.
You can read these posts to learn other actions related to SQLite database:
- Python Creating SQLite Database and Table
- Python Insert Rows into SQLite Database
- Python Update Data in SQLite Database
- Python Select Data Table in SQLite Database
For example, we have a SQLite database located at D:\ToriCode\db\contacts.db with the contacts table as below data.
Step 1 - Create connection to the SQLite database
Firstly, we need to create a connection to the SQLite database.
import sqlite3
from sqlite3 import Error
connection = None
try:
connection = sqlite3.connect('D:\ToriCode\db\contacts.db')
except Error as e:
print(e)
finally:
if connection:
print('Connect to database successfully.')
Step 2- Execute the Delete SQL script to delete a SQLite data row
This step to implement a Python function to delete a record by its id column.
def delete_contact_by_id(conn, id):
sql_delete = ''' DELETE FROM contacts
WHERE id = ?
'''
try:
cursor = conn.cursor()
cursor.execute(sql_delete, (id,))
connection.commit()
except Exception as e:
print(e)
finally:
print('Execute Delete SQL successfully.')
Execute Python function above to delete record with id 2.
delete_contact_by_id(connection, 2)
connection.close()
Complete Python program code.
import sqlite3
from sqlite3 import Error
connection = None
try:
connection = sqlite3.connect('D:\ToriCode\db\contacts.db')
except Error as e:
print(e)
finally:
if connection:
print('Connect to database successfully.')
def delete_contact_by_id(conn, id):
sql_delete = ''' DELETE FROM contacts
WHERE id = ?
'''
try:
cursor = conn.cursor()
cursor.execute(sql_delete, (id,))
connection.commit()
except Exception as e:
print(e)
finally:
print('Execute Delete SQL successfully.')
delete_contact_by_id(connection, 2)
connection.close()
Output:
Connect to database successfully.
Execute Delete SQL successfully.
Below is the contacts table data after execute the Python program above.