Interface Python with an SQL Database
Last Updated :
22 Aug, 2022
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.
- In Python, we will be receiving the inputs from various sources.
- Python will work on the inputs and produce the desired output upon certain computations.
- 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:
Similar Reads
Computer Fundamentals Tutorial This Computer Fundamentals Tutorial covers everything from basic to advanced concepts, including computer hardware, software, operating systems, peripherals, etc. Why Learn Computer FundamentalsYour computer can solve complex problem in milliseconds!Helps you understand how computers work and solve
4 min read
Fundamental
Computer HardwareComputer hardware refers to the physical components of a computer that you can see and touch. These components work together to process input and deliver output based on user instructions. In this article, weâll explore the different types of computer hardware, their functions, and how they interact
10 min read
What is a Computer Software?Computer Software serves as the backbone of all digital devices and systems. It is an integral part of modern technology. Unlike hardware which comprises physical components, software is intangible and exists as a code written in programming language. This article focuses on discussing computer soft
8 min read
Central Processing Unit (CPU)The Central Processing Unit (CPU) is like the brain of a computer. Itâs the part that does most of the thinking, calculating, and decision-making to make your computer work. Whether youâre playing a game, typing a school assignment, or watching a video, the CPU is busy handling all the instructions
6 min read
Input DevicesInput devices are important parts of a computer that help us communicate with the system. These devices let us send data or commands to the computer, allowing it to process information and perform tasks. Whether it's typing on a keyboard or clicking a mouse, these devices enable us to interact with
11 min read
Output DevicesOutput devices are hardware that display or produce the results of a computer's processing. They convert digital data into formats we can see, hear, or touch. The output device may produce audio, video, printed paper or any other form of output. Output devices convert the computer data to human unde
9 min read
Memory
Computer MemoryMemory is the electronic storage space where a computer keeps the instructions and data it needs to access quickly. It's the place where information is stored for immediate use. Memory is an important component of a computer, as without it, the system wouldnât operate correctly. The computerâs opera
9 min read
What is a Storage Device? Definition, Types, ExamplesThe storage unit is a part of the computer system which is employed to store the information and instructions to be processed. A storage device is an integral part of the computer hardware which stores information/data to process the result of any computational work. Without a storage device, a comp
11 min read
Primary MemoryPrimary storage or memory is also known as the main memory, which is the part of the computer that stores current data, programs, and instructions. Primary storage is stored in the motherboard which results in the data from and to primary storage can be read and written at a very good pace.Need of P
4 min read
Secondary MemorySecondary memory, also known as secondary storage, refers to the storage devices and systems used to store data persistently, even when the computer is powered off. Unlike primary memory (RAM), which is fast and temporary, secondary memory is slower but offers much larger storage capacities. Some Ex
7 min read
Hard Disk Drive (HDD) Secondary MemoryPrimary memory, like RAM, is limited and volatile, losing data when power is off. Secondary memory solves this by providing large, permanent storage for data and programs.A hard disk drive (HDD) is a fixed storage device inside a computer that is used for long-term data storage. Unlike RAM, HDDs ret
11 min read
Application Software
MS Word Tutorial - Learn How to Use Microsoft Word (2025 Updated)Microsoft Word remains one of the most powerful word processing program in the world. First released in 1983, this word processing software has grown to serve approximately 750 million people every month. Also, MS Word occupies 4.1% of the market share for productivity software.With features like re
9 min read
MS Excel Tutorial - Learn Excel Online FreeExcel, one of the powerful spreadsheet programs for managing large datasets, performing calculations, and creating visualizations for data analysis. Developed and introduced by Microsoft in 1985, Excel is mostly used in analysis, data entry, accounting, and many more data-driven tasks.Now, if you ar
11 min read
What is a Web Browser and How does it Work?The web browser is an application software used to explore the World Wide Web (WWW). It acts as a platform that allows users to access information from the Internet by serving as an interface between the client (user) and the server. The browser sends requests to servers for web documents and servic
4 min read
Excel SpreadsheetAn Excel spreadsheet, called a workbook, contains one or more worksheets, each a grid of 1,048,576 rows and 16,384 columns for data management. Workbooks organize related data across multiple worksheets in a single file.1. Understanding Excel Workbooks and WorksheetsWorkbook: A single Excel file con
4 min read
System Software
Programming Languages
C Programming Language TutorialC is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
4 min read
Python Tutorial - Learn Python Programming LanguagePython is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
7 min read
Java TutorialJava is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
7 min read
JavaScript TutorialJavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
8 min read