How to Delete a Specific Row from SQLite Table using Python ?
Last Updated :
28 Apr, 2021
In this article, we will discuss how to delete of a specific row from the SQLite table using Python.
In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause.
Syntax:
DELETE FROM table_name
WHERE condition;
We are going to create a table and then perform deletion operations in it.
Python3
import sqlite3
connection = sqlite3.connect( 'my_database.db' )
connection.execute(
)
print ( "Ship table created successfully" )
connection.close()
|
Output:
Ship table created successfully
Example 1:
Python program to insert data and delete data where 2 is ship id.
Python3
import sqlite3
connection = sqlite3.connect( 'my_database.db' )
connection.execute( "INSERT INTO ship VALUES (1, 'tata-hitachi','noida' )" )
connection.execute( "INSERT INTO ship VALUES (2, 'tata-mumbai','mumbai' )" )
connection.execute( "INSERT INTO ship VALUES (3, 'tata-express','hyderabad' )" )
cursor = connection.execute( "SELECT * from ship" )
print ( "Actual data" )
for row in cursor:
print (row)
connection.execute( "DELETE from ship where ship_id=2" )
print ( "After deleting ship id = 2 row" )
cursor = connection.execute( "SELECT * from ship" )
for row in cursor:
print (row)
connection.close()
|
Output:
Example 2:
In this example delete data where the ship address is hyderabad on the same table.
Python3
import sqlite3
connection = sqlite3.connect( 'my_database.db' )
connection.execute( "INSERT INTO ship VALUES (1, 'tata-hitachi','noida' )" )
connection.execute( "INSERT INTO ship VALUES (2, 'tata-mumbai','mumbai' )" )
connection.execute( "INSERT INTO ship VALUES (3, 'tata-express','hyderabad' )" )
cursor = connection.execute( "SELECT * from ship" )
print ( "Actual data" )
for row in cursor:
print (row)
connection.execute( "DELETE from ship where ship_destination='hyderabad'" )
print ( "After deleting ship address = hyderabad row" )
cursor = connection.execute( "SELECT * from ship" )
for row in cursor:
print (row)
connection.close()
|
Output:
Share your thoughts in the comments
Please Login to comment...