The Wayback Machine - https://web.archive.org/web/20240913055036/https://www.geeksforgeeks.org/python-sqlite-crud-operations/
Open In App

Python SQLite – CRUD Operations

Last Updated : 21 Apr, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will go through the CRUD Operation using the SQLite module in Python.

CRUD Operations

The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let’s discuss these operations one by one with the help of examples.

CREATE

The create command is used to create the table in database. First we will go through its syntax then understand with an example.

Syntax: CREATE TABLE table_name ( Attr1 Type1, Attr2 Type2, â€Ķ , Attrn Typen ) ;

In this example, we will create a table named “gfg” with three attributes:

  1. name
  2. points
  3. accuracy

Python




# Python code to create a relation 
# using SQLite3
  
# import the sqlite3 package
import sqlite3  
  
# create a database named backup
cnt = sqlite3.connect("backup.dp")  
  
# create a table named gfg
cnt.execute('''CREATE TABLE gfg(
NAME TEXT,
POINTS INTEGER,
ACCURACY REAL);''')


Output:

INSERT

This refers to the insertion of new data into the table. Data is inserted in the form of a tuple. The number of attributes in the tuple must be equal to that defined in the relation schema while creating the table.

1. To insert attributes in the order specified in the relation schema:
Syntax: INSERT INTO tableName VALUES ( value1, value2, â€Ķ valuen )
 
2.To insert attributes in the order specified in the relation schema or in a different order:
INSERT INTO tableName ( Attribute1, Attribute3, Attribute2 . . . ) VALUES ( value1, value3, value2 . . . )

The program below demonstrates the addition of three tuples to the gfg relation that was created earlier.

Python3




# Python3 Code to insert data into
# the database
  
# Insert three tuples into the gfg table
# insert in default order
cnt.execute('''INSERT INTO gfg VALUES(
'Count Inversion',20,80.5);''')
  
# insert in different order
cnt.execute('''INSERT INTO gfg(ACCURACY, POINTS, NAME) VALUES(
90.5, 15, 'Kadanes Algo');''')
  
cnt.execute('''INSERT INTO gfg(NAME, ACCURACY, POINTS) VALUES(
'REVERSE STR', 100, 5);''')
  
# commit changes to the database
cnt.commit()


Output:

READ

This refers to reading data from a database. A read statement has three clauses:

  1. SELECT: Takes as the predicate the attributes to be queried, use * for all attributes.
  2. FROM: Takes as the predicate a relation.
  3. WHERE: Takes as the predicate a condition, this is not compulsory.

After executing a read statement in python SQLite3, an iterable cursor object is returned. This can be used to print data.

Example: SELECT NAME, POINTS, ACCURACY FROM gfg WHERE ACCURACY>85;

The program below demonstrates the usage of the read statement.

Python3




# Python3 code to read data from a table
  
print('Name, Points and Accuracy from '
      'records with accuracy greater than 85')
  
cursor = cnt.execute('''SELECT * FROM gfg WHERE ACCURACY>85;''')
  
# print data using the cursor object
for i in cursor:
    print(i[0]+"    "+str(i[1])+"   "+str(i[2]))
  
print('')  # Print new line
  
print('Name, Accuracy from '
      'records with accuracy greater than 85')
  
cursor = cnt.execute('''SELECT NAME, ACCURACY FROM
gfg WHERE ACCURACY>85;''')
  
# print data using the cursor object
for i in cursor:
    print(i[0]+"    "+str(i[1]))


Output:

UPDATE

This refers to the updating of tuple values already present in the table.

Syntax: UPDATE tableName SET Attribute1 = Value1 , Attribute2 = Value2 , . . . WHERE condition;
The WHERE clause must be included, else all records in the table will be updated.

EXAMPLE: UPDATE gfg SET POINTS=POINTS+5 WHERE POINTS<20;

The program below demonstrates the usage of the update statement.

Python3




# Python3 code to update records in a database
  
# Print records before updation
cursor = cnt.execute('''SELECT * FROM gfg''')
print('Before Updation')
for i in cursor:
    print(i[0]+"    "+str(i[1])+"    "+str(i[2]))
  
print('')  # print a newline
  
# Execute an Update statement
cnt.execute('''UPDATE gfg SET POINTS=POINTS+5 WHERE
POINTS<20;''')
  
cursor = cnt.execute('''SELECT * FROM gfg''')
print('After Updation')
for i in cursor:
    print(i[0]+"    "+str(i[1])+"    "+str(i[2]))


Output:

DELETE

This refers to the deletion of the tuple present in the table.

SYNTAX: DELETE FROM tableName WHERE condition

If WHERE clause is not used then all the records will be deleted.

EXAMPLE: DELETE FROM gfg WHERE ACCURACY>91

The program below demonstrates the usage of the delete statement.

Python3




# Python3 code to delete records from database
  
# Print records before deletion
cursor = cnt.execute('''SELECT * FROM gfg''')
print('Before Deletion')
for i in cursor:
    print(i[0]+"    "+str(i[1])+"    "+str(i[2]))
  
print('')  # print a newline
  
# Execute a delete statement
cnt.execute('''DELETE FROM gfg WHERE ACCURACY>91;''')
  
cursor = cnt.execute('''SELECT * FROM gfg''')
print('After Deletion')
for i in cursor:
    print(i[0]+"    "+str(i[1])+"    "+str(i[2]))


Output:



Similar Reads

CRUD Operations on Postgres using Async Database In Python
CRUD stands for Create, Read, Update and Delete Operations. All these Operations can be made Asynchronous using the Async Database Connection. After making Async Connection to Postgres Database, the performance of the Application improves significantly as all the operations are performed Concurrently rather than in a sequential manner. The Async da
3 min read
Perform PostgreSQL CRUD operations from Python
The DDL is comprised of the Create, Read, Update, Delete (CRUD) operations which form the backbone of any SQL database system. Let us discuss how to perform CRUD operations on a PostgreSQL database using python. Pyscopg2 is the most preferred mode and is widely used to connect the PostgreSQL database using python. Pyscopg2 is a Database API which i
7 min read
FastAPI - Crud Operations
We will explore how to implement CRUD operations with FastAPI. CRUD operations are essential in any web application, including creating new records, retrieving existing records, updating existing records, and deleting records from a database. What is CRUD in FastAPI?CRUD refers to the basic operations that can be performed on data in a database. It
5 min read
CRUD Operation in Python using MySQL
In this article, we will be seeing how to perform CRUD (CREATE, READ, UPDATE and DELETE) operations in Python using MySQL. For this, we will be using the Python MySQL connector. For MySQL, we have used Visual Studio Code for python. Before beginning we need to install the MySQL connector with the command: pip install mysql-connector-python-rf In or
6 min read
CRUD Operation on Oracle Database Using Python
In this article, we will learn how to perform CURD operations on an Oracle Database by using Python. Oracle Database is a Database Management System produced and marketed by Oracle Corporation. It supports the Structured Query language (SQL) to Manage and Manipulate the Data. As a prerequisite, you must have installed the Oracle database in your sy
4 min read
Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Update, Delete) operations. CRUD can be best explain
7 min read
Django REST API - CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around the Django Framework. There are three stages before creating an API through the REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, and Creating a URL for mapping to the views. Django REST
7 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
Introduction to SQLite in Python
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to SQ
3 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
How to store Python functions in a Sqlite table?
SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard HÃĪring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. To use t
3 min read
Python SQLite - JOIN Clause
In this article, we discuss the JOIN clause in SQLite using the sqlite3 module in Python. But at first let's see a brief about join in SQLite. Join Clause A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows: INNER JOIN (OR JOIN) - Gives the records that have common attrib
5 min read
Creating a sqlite database from CSV with Python
Prerequisites: PandasSQLite SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embed
2 min read
Python SQLite - Create Table
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to create a table: CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); N
1 min read
SQLite Datatypes and its Corresponding Python Types
SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQLite3 comes default with python. In this article, w
3 min read
How to connect to SQLite database that resides in the memory using Python ?
In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost a
3 min read
How to Delete a Specific Row from SQLite Table using Python ?
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
3 min read
How to Update all the Values of a Specific Column of SQLite Table using Python ?
In this article, we are going to update all the values of a specific column of a given SQLite table using Python. In order to update all the columns of a particular table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple colu
3 min read
Python SQLite - ORDER BY Clause
In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order.ASC to sort in ascending order.
3 min read
Python SQLite - LIMIT Clause
In this article, we are going to discuss the LIMIT clause in SQLite using Python. But first, let's get a brief about the LIMIT clause. If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement. Syntax: SELECT colum
2 min read
Python SQLite - DROP Table
In this article, we will discuss the DROP command in SQLite using Python. But first, let's get a brief about the drop command. DROP is used to delete the entire database or a table. It deleted both records in the table along with the table structure. Syntax: DROP TABLE TABLE_NAME; For dropping table, we will first create a database and a table in i
2 min read
Change SQLite Connection Timeout using Python
In this article, we will discuss how to change the SQLite connection timeout when connecting from Python. What is a connection timeout and what causes it? A connection timeout is an error that occurs when it takes too long for a server to respond to a user's request. Connection timeouts usually occur when there are multiple active connections to a
3 min read
Python SQLite - Deleting Data in Table
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: C/C++ Code import sqlite3 # Connec
2 min read
How to Count the Number of Rows of a Given SQLite Table using Python?
In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. To create the database
2 min read
How to Alter a SQLite Table using Python ?
In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module. We can do this by using ALTER statement. It allows to: Add one or more column to the tableChange the name of the table.Adding a column to a table The syntax of ALTER TABLE to add a new column in an existing table in SQLite
3 min read
How to Show all Columns in the SQLite Database using Python ?
In this article, we will discuss how we can show all columns of a table in the SQLite database from Python using the sqlite3 module. Approach:Connect to a database using the connect() method.Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it.Use the description keyword o
3 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
Article Tags :
Practice Tags :