Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python MySQL
Next article icon

SQL using Python

Last Updated : 03 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, integrating SQLite3 with Python is discussed. Here we will discuss all the CRUD operations on the SQLite3 database using Python. CRUD contains four major operations - 

CRUD operations SQLite3 and Python

Note: This needs a basic understanding of SQL. 

Here, we are going to connect SQLite with Python. Python has a native library for SQLite3 called sqlite3. Let us explain how it works. 

Connecting to SQLite Database

  • To use SQLite, we must import sqlite3.
import sqlite3
  • Then create a connection using connect() method and pass the name of the database you want to access if there is a file with that name, it will open that file. Otherwise, Python will create a file with the given name.
sqliteConnection = sqlite3.connect('gfg.db')
  • After this, a cursor object is called to be capable to send commands to the SQL. 
cursor = sqliteConnection.cursor()

Example: Connecting to SQLite3 database using Python

Python3
import sqlite3  # connecting to the database connection = sqlite3.connect("gfg.db")  # cursor crsr = connection.cursor()  # print statement will execute if there # are no errors print("Connected to the database")  # close the connection connection.close() 

Output:

Connected to the database

Cursor Object

Before moving further to SQLite3 and Python let's discuss the cursor object in brief. 

  • The cursor object is used to make the connection for executing SQL queries.
  • It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database. 
  • The cursor is a control structure used to traverse and fetch the records of the database. 
  • All the commands will be executed using cursor object only.

Executing SQLite3 Queries - Creating Tables

After connecting to the database and creating the cursor object let's see how to execute the queries.

  • To execute a query in the database, create an object and write the SQL command in it with being commented. Example:- sql_comm = ”SQL statement”
  • And executing the command is very easy. Call the cursor method execute() and pass the name of the sql command as a parameter in it. Save a number of commands as the sql_comm and execute them. After you perform all your activities, save the changes in the file by committing those changes and then lose the connection. 

Example: Creating SQLite3 tables using Python

In this example, we will create the SQLite3 tables using Python. The standard SQL command will be used for creating the tables.

Python
import sqlite3  # connecting to the database connection = sqlite3.connect("gfg.db")  # cursor crsr = connection.cursor()  # SQL command to create a table in the database sql_command = """CREATE TABLE emp (  staff_number INTEGER PRIMARY KEY,  fname VARCHAR(20),  lname VARCHAR(30),  gender CHAR(1),  joining DATE);"""  # execute the statement crsr.execute(sql_command)  # close the connection connection.close() 

Output:

python sqlite3 create table

Inserting into Table

To insert data into the table we will again write the SQL command as a string and will use the execute() method.

Example 1: Inserting Data into SQLite3 table using Python

Python3
# Python code to demonstrate table creation and # insertions with SQL  # importing module import sqlite3  # connecting to the database connection = sqlite3.connect("gfg.db")  # cursor crsr = connection.cursor()  # SQL command to insert the data in the table sql_command = """INSERT INTO emp VALUES (23, "Rishabh",\ "Bansal", "M", "2014-03-28");""" crsr.execute(sql_command)  # another SQL command to insert the data in the table sql_command = """INSERT INTO emp VALUES (1, "Bill", "Gates",\ "M", "1980-10-28");""" crsr.execute(sql_command)  # To save the changes in the files. Never skip this. # If we skip this, nothing will be saved in the database. connection.commit()  # close the connection connection.close() 

Output:

python sqlite3 insert data

Example 2: Inserting data input by the user

Python3
# importing module import sqlite3  # connecting to the database connection = sqlite3.connect("gfg.db")  # cursor crsr = connection.cursor()  # primary key pk = [2, 3, 4, 5, 6]  # Enter 5 students first names f_name = ['Nikhil', 'Nisha', 'Abhinav', 'Raju', 'Anshul']  # Enter 5 students last names l_name = ['Aggarwal', 'Rawat', 'Tomar', 'Kumar', 'Aggarwal']  # Enter their gender respectively gender = ['M', 'F', 'M', 'M', 'F']  # Enter their joining data respectively date = ['2019-08-24', '2020-01-01', '2018-05-14', '2015-02-02', '2018-05-14']  for i in range(5):      # This is the q-mark style:     crsr.execute('INSERT INTO emp VALUES ({pk[i]}, "{f_name[i]}", "{l_name[i]}", "{gender[i]}", "{date[i]}")')  # To save the changes in the files. Never skip this. # If we skip this, nothing will be saved in the database. connection.commit()  # close the connection connection.close() 

Output:

insert into table python sqlite3

Fetching Data

In this section, we have discussed how to create a table and how to add new rows in the database. Fetching the data from records is simple as inserting them. The execute method uses the SQL command of getting all the data from the table using “Select * from table_name” and all the table data can be fetched in an object in the form of a list of lists.

Example: Reading Data from sqlite3 table using Python

Python
# importing the module import sqlite3  # connect with the myTable database connection = sqlite3.connect("gfg.db")  # cursor object crsr = connection.cursor()  # execute the command to fetch all the data from the table emp crsr.execute("SELECT * FROM emp")  # store all the fetched data in the ans variable ans = crsr.fetchall()  # Since we have already selected all the data entries # using the "SELECT *" SQL command and stored them in # the ans variable, all we need to do now is to print # out the ans variable for i in ans:     print(i) 

Output:

fetch data python sqlite3

Note: It should be noted that the database file that will be created will be in the same folder as that of the python file. If we wish to change the path of the file, change the path while opening the file.

Updating Data

For updating the data in the SQLite3 table we will use the UPDATE statement. We can update single columns as well as multiple columns using the UPDATE statement as per our requirement.

UPDATE table_name SET column1 = value1, column2 = value2,…   WHERE condition; 

In the above syntax, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated. 

Example: Updating SQLite3 table using Python

Python3
# Import module import sqlite3  # Connecting to sqlite conn = sqlite3.connect('gfg.db')  # Creating a cursor object using # the cursor() method cursor = conn.cursor()  # Updating cursor.execute('''UPDATE emp SET lname = "Jyoti" WHERE fname="Rishabh";''')  # Commit your changes in the database conn.commit()  # Closing the connection conn.close() 

Output:

update sqlite3 table using Python

Deleting Data

For deleting the data from the SQLite3 table we can use the delete command. 

DELETE FROM table_name [WHERE Clause]

Example: Deleting from SQLite3 table using Python

Python3
# Import module import sqlite3  # Connecting to sqlite conn = sqlite3.connect('gfg.db')  # Creating a cursor object using # the cursor() method cursor = conn.cursor()  # Updating cursor.execute('''DELETE FROM emp WHERE fname="Rishabh";''')  # Commit your changes in the database conn.commit()  # Closing the connection conn.close() 

Output:

Deleting from SQLite3 table using Python

Deleting Table

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;

Example: Drop SQLite3 table using Python

Total tables in the gfg.db before dropping

drop sqlite3 table using Python

Now let's drop the Student table and then again check the total table in our database.

Python3
# Import module import sqlite3  # Connecting to sqlite conn = sqlite3.connect('gfg.db')  # Creating a cursor object using # the cursor() method cursor = conn.cursor()  # Updating cursor.execute('''DROP TABLE Student;''')  # Commit your changes in the database conn.commit()  # Closing the connection conn.close() 

Output:

Dropping SQLite3 table using Python

Note: To learn more about SQLit3 with Python refer to our Python SQLite3 Tutorial. 


Next Article
Python MySQL

R

Rishabh Bansal
Improve
Article Tags :
  • Python
  • SQL
Practice Tags :
  • python

Similar Reads

    Python Database Tutorial
    Python being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system. In this t
    4 min read
    How to Connect Python with SQL Database?
    In this article, we will learn how to connect SQL with Python using the MySQL Connector Python module. Below diagram illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data.SQL connection with Pyth
    2 min read
    SQL using Python
    In this article, integrating SQLite3 with Python is discussed. Here we will discuss all the CRUD operations on the SQLite3 database using Python. CRUD contains four major operations -  Note: This needs a basic understanding of SQL.  Here, we are going to connect SQLite with Python. Python has a nati
    7 min read
    Python MySQL
    Python MySQL Connector is a Python driver that helps to integrate Python and MySQL. This Python MySQL library allows the conversion between Python and MySQL data types. MySQL Connector API is implemented using pure Python and does not require any third-party library.  This Python MySQL tutorial will
    9 min read
    Python SQLite
    Python SQLite3 module is used to integrate the SQLite database with Python. It is a standardized Python DBI API 2.0 and provides a straightforward and simple-to-use interface for interacting with SQLite databases. There is no need to install this module separately as it comes along with Python after
    4 min read
    Python MongoDB Tutorial
    MongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
    2 min read
    Introduction to Psycopg2 module in Python
    Psycopg is the most popular PostgreSQL adapter used in  Python.  Its works on the principle of the whole implementation of Python DB API 2.0 along with the thread safety (the same connection is shared by multiple threads). It is designed to perform heavily multi-threaded applications that usually cr
    4 min read
    Top 7 Databases to Learn in 2025
    A database is just like a room in an office where all the files and important information can be stored related to a project. Every company needs a database to store and organize the information. The information that we store can be very sensitive, so we always have to be careful while accessing or
    10 min read
    Interface Python with an SQL Database
    Python is an easy-to-learn language and connectivity of python with any SQL database is a much-desired option to have the persistence feature. Python is an object-oriented programming language and it is open source. Newcomers to the software industry including school children too can learn Python ea
    8 min read
    Access Relation Databases with Python
    Databases are powerful tools for data scientists. DB-API is Python's standard API used for accessing databases. It allows you to write a single program that works with multiple kinds of relational databases instead of writing a separate program for each one. This is how a typical user accesses datab
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences