Python SQLite – Deleting Data in Table
Last Updated :
20 Jul, 2021
In this article, we will discuss how we can delete data in the table in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to delete data from a table:
DELETE FROM table_name [WHERE Clause]
To create the database, we will execute the following code:
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
cursor_obj.execute( "DROP TABLE IF EXISTS GEEK" )
table =
cursor_obj.execute(table)
connection_obj.execute( )
connection_obj.execute( )
connection_obj.execute( )
connection_obj.execute( )
connection_obj.execute( )
connection_obj.execute( )
connection_obj.execute( )
connection_obj.commit()
connection_obj.close()
|
Output:
Now we will create a python program to delete the row in a table:
Approach:
- Import the required module.
- Establish the connection or create a connection object with the database using to connect() function of the sqlite3 module.
- Create a Cursor object by calling the cursor() method of the Connection object.
- Finally, trigger to execute() method on the cursor object, bypassing a DELETE statement as a parameter to it.
Example 1: (Delete some data)
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
cursor_obj.execute( "DELETE FROM GEEK WHERE Score < 15" )
connection_obj.commit()
connection_obj.close()
|
Output:
Example 2: (Delete all data)
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
cursor_obj.execute( "SELECT * FROM GEEK" )
print (cursor_obj.fetchall())
cursor_obj.execute( "DELETE FROM GEEK" )
print ()
print ( "After deleting all rows" )
cursor_obj.execute( "SELECT * FROM GEEK" )
print (cursor_obj.fetchall())
connection_obj.commit()
connection_obj.close()
|
Output:
Share your thoughts in the comments
Please Login to comment...