written 2.7 years ago by | modified 2.7 years ago by |
Program to demonstrate CRUD (create, read, update and delete) operations on database (SQLite/ MySQL) using python.
written 2.7 years ago by | modified 2.7 years ago by |
Program to demonstrate CRUD (create, read, update and delete) operations on database (SQLite/ MySQL) using python.
written 2.7 years ago by | • modified 2.7 years ago |
Python has built-in support for SQLite database through the sqlite3 module.
The CRUD represents the basic database operations such as Create, Read, Update and Delete.
SQLite database is an open-source and self-configured relational database engine that doesn't require a server configuration like other databases.
SQLite is freely downloadable from its official website.
To create a new SQLite database, navigate from the command prompt to the folder where you have unzipped the archive and enter the commands to perform the required operations.
The first step is to create a database in SQLite using a command prompt.
Here, we create the database named "database.db" and after creating this any SQL query will be executed by using Python.
To do this first required to connect with SQLite database.
import sqlite3
db=sqlite3.connect('database.db')
Methods used in the Python Program to perform various SQLite database operations are as follows:
Python Methods | Description for the Method |
---|---|
The connect() method | It returns a connection to the object that refers to the existing database or a new database if it doesn't exist. |
The cursor() method | It returns a Cursor object which uses this connection. It enables working with the database and acts as a handle for a given SQL query to READ one or more rows from the database table. cur=db.cursor() |
The execute() method | It executes the SQL query in a string parameter. If an incorrect SQL query is used then it creates an Exception. Therefore, is always placed within the try and except block. |
The commit() method | It ensures transaction control. It saves the effect of the right SQL query persistently. |
The rollback() method | It ensures transaction control. It undone the pending transactions if the SQL query fails, the resulting exception is processed by the except block. |
The fetchone() method | Fetches the next available record from the result set. It is a tuple consisting of values of each column of the fetched record. It uses a loop to iterate through the result set. |
The fetchall() method | Fetches all remaining records in the form of a list of tuples. Each tuple corresponds to one record and contains values of each column in the table. |
The close() method | It closes the connection with the database permanently. Attempts to use the connection after calling this method will raise a DB-API Error. |
Basic SYNTAX for execute() method:
try:
cur=db.cursor()
cur.execute("SQL Query")
db.commit()
print ("Success Message")
except:
print ("Error Message")
db.rollback()
db.close()
import sqlite3
db=sqlite3.connect('database.db')
try:
cur =db.cursor()
cur.execute('''CREATE TABLE book (
BookID INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT (20) NOT NULL,
author TEXT (20),
publisher TEXT (20));''')
print ('Table Created Successfully')
except:
print ('Error in Operation')
db.rollback()
db.close()
.tables
command in the SQLite shell as follows:import sqlite3
db=sqlite3.connect('database.db')
qry="insert into book (title, author, publisher) values('Internet Programming', 'Binita Mayekar', 'Ques10');"
try:
cur=db.cursor()
cur.execute(qry)
db.commit()
print ("One Record Added Successfully")
except:
print ("Error in operation")
db.rollback()
db.close()
import sqlite3
db=sqlite3.connect('database.db')
sql="SELECT * from book;"
cur=db.cursor()
cur.execute(sql)
while True:
record=cur.fetchone()
if record==None:
break
print (record)
db.close()
import sqlite3
db=sqlite3.connect('database.db')
qry="update book set author=? where title=?;"
try:
cur=db.cursor()
cur.execute(qry, ('AUTHOR','abc'))
db.commit()
print("Record Updated Successfully")
except:
print("Error in Operation")
db.rollback()
db.close()
select *book
command in SQLite shell OR again run fetchone() or fectchall() method of python program to check table data.import sqlite3
db=sqlite3.connect('database.db')
qry="DELETE from book where publisher=?;"
try:
cur=db.cursor()
cur.execute(qry, ('pqr',))
db.commit()
print("Record Deleted Successfully")
except:
print("Error in Operation")
db.rollback()
db.close()
select *book command
in SQLite shell OR again run fetchone() or fectchall() method of python program to check table data.select *book
command in SQLite shell using the command prompt that shows the third row where publisher = pqr deleted from the table.