Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • CBSE
  • CBSE Notes
  • Class 12 Syllabus
  • Class 12 Revision Notes
  • Maths Notes Class 12
  • Physics Notes Class 12
  • Chemistry Notes Class 12
  • Biology Notes Class 12
  • NCERT Solutions Class 12 Maths
  • RD Sharma Solutions Class 12
Open In App
Next Article:
Access Relation Databases with Python
Next article icon

Interface Python with an SQL Database

Last Updated : 22 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 easily. Python can be downloaded easily according to the operating system and all novice users also can do it easily.

SQL Server is a database that is helpful for persistent data. Whenever we want to store a lot of information, we are dependent on a database. It can be any database like MySQL, SQL Server, and even NoSQL database like MongoDB. Information is stored across multiple tables in a database like MySQL or SQLServer. Under a database, multiple tables can be created. Each and every table can have multiple columns. A table can have numerous rows where each and every row represents the information of either student/employee/exam etc., That means each and every row must be uniquely identified by means of a Primary Key. Apart from this, we have different keys like Unique Key, Foreign Key, etc. to access data.

The necessity of interfacing Python with SQL database

All database (RDBMS) is required to store the data, and manage the data (in the way of inserting/deleting/updating) the data. The way of handling these sets of operations is called CRUD operations (CREATE/READ/UPDATE/DELETE). Python is a user-friendly language and it can able to get connected to any database easily via the above ways. Once proper installation is done, Python and that database can be connected. Any CRUD operations can able to get handled easily.

  1. In Python, we will be receiving the inputs from various sources.
  2. Python will work on the inputs and produce the desired output upon certain computations.
  3. The final output can be stored in the database if we interface with Python and SQL databases.

For interfacing Python and the database, we need to install the desired installations. For each and every SQL database (RDBMS), we need to install it differently. That differs with the operating system as well

For sqlite3 Module:

pip install pysqlite3 

In earlier versions of python, it will be 

pip install pysqlite

For anaconda environment

conda install sqlite3

Similarly for MySQL, it will be

pip install mysqlclient  --older versions  (1.2.x versions (legacy Python only))  pip install MySQL-python

SQL Server:

pip install pymssql

Connecting MySQL with Python

The following program will show how to connect MySQL with Python

Python3

# Python3 Program to connect MySQL to Python
# As we are connecting mysql, this is needed
import mysql.connector
db_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root",  
    
  # Change your password here
  passwd="admin",  
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
  
# Database is in scope now
my_database = db_connection.cursor()
                      
                       

Once we get the connection, we need to see how to insert the data. Let us assume that in MySQL, there is a table named ‘GEEKPORTALLOGIN’ available. Providing the scripts to create a table in MySQL as well

drop table GEEKSFORGEEKS.GEEKPORTALLOGIN;  # If we want to drop the table if already exists

— Create the table GEEKPORTALLOGIN 

CREATE TABLE GEEKSFORGEEKS.GEEKPORTALLOGIN (id INT NOT NULL,

   loginName VARCHAR(20) default NULL,

   password VARCHAR(45) default NULL,

   PRIMARY KEY (id)

);

Inserting Data using Python

We can insert data into the database using Python. The following methods are used to insert data:

1. execute(): This function is used to prepare a database operation and run it. It takes parameters in the form of a series or mapping. 

Syntax:

execute(operation[, parameters])

2. executemany(): This function is used to build a database action and run it against all of the parameter tuples in the series of parameters. It is especially used for database update instructions. 

Syntax:

executemany(operation, sequence_of_parameters)

The following examples will show how to insert data into the database using Python.

Example 1:

Python3

# Python Program to insert data into database 
import mysql.connector
  
db_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root",  
    
  # Change your password here
  passwd="admin",  
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
my_database = db_connection.cursor()
  
# Get the inputs. Usually from frontend we may 
# get inputs and they will be passed to Python
# Here let us get from Python itself
loginName = input("Enter a login Name : ");
  
# For sample only password is getting shown here
password = input("Enter a password : "); 
idx = "1"
sql_statement = "INSERT INTO geekportallogin (id,loginName,password) values(%s,%s,%s)"
values = (idx,loginName,password)
  
# Execute will help to insert a single row of data
my_database.execute(sql_statement,values)
  
# To save the data into the database under the particular table
db_connection.commit()
                      
                       

Output:

 

Example 2: 

Similarly, we can insert many rows of data together. This will be the ideal scenario when we are doing bulk inserts

Python3

# Python3 program to insert multiple rows
import mysql.connector
  
sample_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root",  
    
  # Change your password here
  passwd="admin",  
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
sample_database = sample_connection.cursor()
  
# Inserting data
values = [ ("2","geekb","geekb"),
  
           ("3","geekc","geekc"),
  
           ("4","geekd","geekd")  
          ]
sql_statement = "INSERT INTO geekportallogin (id,loginName,password)  values(%s,%s,%s)"
  
# As we are going to insert multiple values, we need to use executemany
sample_database.executemany(sql_statement,values)
  
# To save the data into the database under the particular table
sample_connection.commit()  
                      
                       

Output:

 

Fetching Data using Python

We can also fetch data using Python from the MySql database. To fetch the data from the MySql database we can use the following methods:

1. fetchall(): This function will fetch all the tuples from the last executed statement from the table. If there are no more rows available, then it will return an empty list.

Syntax: 

data = cursor.fetchall()

2. fetchone(): This function is used to fetch one row from the specified table.

Syntax: 

data = cursor.fetchone()

2. fetchmany(): This function is used to fetch the next set of rows from a query result and If there are no more rows available, then it will return a blank list. The default size of fetchmany() function is one only. It takes only one argument which represents the number of rows to fetch. 

Syntax:

data = cursor.fetchmant([size = cursor.arraySize])

The following examples will show how to fetch the MySQL data from Python. 

Example 1:

Python3

# Python program to fetch data from MySql database
import mysql.connector
sample_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root",  
    
  # Change your password here
  passwd="admin", 
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
sample_database = sample_connection.cursor()
  
# Specify your correct table name here
sql_statement = "SELECT * FROM GEEKPORTALLOGIN" 
sample_database.execute(sql_statement)
  
# This step is used to get all the records as a list of tuples
sample_output = sample_database.fetchall()  
  
# Iterate over the output
for value in sample_output:
  print(value)
                      
                       

Output:

 

Example 2: 

Python3

# Python program to fetch data from MySql database
import mysql.connector
sample_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root",  
    
  # Change your password here
  passwd="admin",  
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
sample_database = sample_connection.cursor()
  
# Specify your correct table name here
sql_statement = "SELECT * FROM GEEKPORTALLOGIN" 
sample_database.execute(sql_statement)
  
# fetchmany(size=n) will tell n records where
# n can be more than 1
# This step is used to get only 2 records
sample_output = sample_database.fetchmany(size=2)  
  
# Iterate over the output
# Hence we can see only first 2 rows of data
# as we have given size = 2
for value in sample_output:
  print(value)
   
                      
                       

Output:

 

Updating the MySQL data using Python

We can also update the data stored in the MySql database using python. The following example will show how to update the data with the new data. 

Example: 

Python3

# Python program to update data in database
import mysql.connector
  
sample_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root",  
    
  # Change your password here
  passwd="admin",  
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
sample_database = sample_connection.cursor()
  
# Specify the update statement
sql_statement = "UPDATE  GEEKPORTALLOGIN SET loginName = %s WHERE id = %s" 
  
# Provide the values now for loginName and id
  
# First one will indicate for loginName and second one for id
values = ("geeka123","1") 
  
# This will take care of updating values
sample_database.execute(sql_statement,values) 
sample_connection.commit()
                      
                       

Output:

 

Deleting the MySQL data using Python

We can also delete the specific row from the MySql database using python. The following example will show how to delete the specified row from the record.

Example:

Python3

# Python program to delete the row
import mysql.connector
  
sample_connection = mysql.connector.connect(
  host="localhost",
    
  # Change your username here
  user="root", 
    
  # Change your password here
  passwd="admin",  
    
  # Need to point for the correct db
  database="geeksforgeeks" 
)
sample_database = sample_connection.cursor()
  
# Specify the delete statement
sql_statement = "DELETE FROM  GEEKPORTALLOGIN  WHERE id = %s" 
  
# Provide the values now for id
# We are going to delete for id = 1. 
# This is the syntax we have to follow
values = ("1",) 
  
# This will take care of deleting values
sample_database.execute(sql_statement,values)  
sample_connection.commit()
                      
                       

Output:

 



Next Article
Access Relation Databases with Python
author
priyarajtt
Improve
Article Tags :
  • Class 12
  • School Learning
  • School Programming
  • Computer-Science-Class-12

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. To create a connection
    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 native
    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 one of the most popular NoSQL database. It is a cross-platform, object-oriented database. Basically NoSQL means MongoDB does not store data in the table or relational format rather provide a different mechanism for storage and retrieval of data. This is called BSON which is similar to JSO
    3 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