Deleting the data

Now, we will see an example of deleting data from a table. We are going to do this using the delete statement. Create a delete_data.py script and write the following content in it:

import sqlite3

con_obj = sqlite3.connect("test.db")
with con_obj:
cur_obj = con_obj.cursor()
sql = """
DELETE FROM books
WHERE author = 'John Smith'
"""
cur_obj.execute(sql)

print("Data deleted successfully !!")

Run the script and you will get the following output:

student@ubuntu:~/work $ python3 delete_data.py

Output:
Data deleted successfully !!

In the preceding example, we deleted a record from a table. We used the delete SQL statement. Now, to check whether the data is deleted successfully or not, run retrieve_data.py or start the SQLite console, as follows:

By running retrieve_data.py

Output:
student@ubuntu:~/work$ python3 retrieve_data.py
Title = Pride and Prejudice
Author = Jane Austen

Title = The Lord of the Rings
Author = J. R. R. Tolkien

Title = Murder on the Orient Express
Author = Agatha Christie

Title = A Study in Scarlet
Author = Arthur Conan Doyle

You can see the record whose author was john smith is deleted:

Checking on SQLite console:

Output:
student@ubuntu:~/work$ sqlite3 test.db
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite>
sqlite> select * from books;
Pride and Prejudice|Jane Austen
The Lord of the Rings|J. R. R. Tolkien
Murder on the Orient Express|Agatha Christie
A Study in Scarlet|Arthur Conan Doyle
sqlite>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset