Now on to our Python sqlite3 Delete Row Example! All we need to do is write the usual DELETE SQL statement within the cur.execute() method:
import sqlite3
con = sqlite3.connect('data/sample.db')
cur = con.cursor()
#select rows
for row in cur.execute('SELECT * FROM PlayList'):
print(row)
#OUTPUT
#('2022-01-31', 1, 'Kanye West', 'Fade', 'Life of Pablo', '3:13', 2.99)
#('2022-01-31', 2, 'Kanye West', 'Ultralight Beam', 'Life of Pablo', '5:20', 3.99)
#('2022-01-31', 3, 'Kanye West', 'Famous', 'Life of Pablo', '3:16', 1.99)
cur.execute("DELETE FROM PlayList WHERE id = 1")
#select rows
for row in cur.execute('SELECT * FROM PlayList'):
print(row)
#OUTPUT
#('2022-01-31', 2, 'Kanye West', 'Ultralight Beam', 'Life of Pablo', '5:20', 3.99)
#('2022-01-31', 3, 'Kanye West', 'Famous', 'Life of Pablo', '3:16', 1.99)
con.close()
This is simple. All we are doing is running the DELETE statement against our sample.db in the cur.execute() method.
Click HERE to go to the previous part of this tutorial. Full source code HERE. 👌👌👌