The Wayback Machine - https://web.archive.org/web/20241128102213/https://www.geeksforgeeks.org/python-mysql/
Open In App

Python MySQL

Last Updated : 01 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

python mysql tutorial

This Python MySQL tutorial will help to learn how to use MySQL with Python from basics to advance, including all necessary functions and queries explained in detail with the help of good Python MySQL examples. So, let’s get started.

Installation

To install the Python-mysql-connector module, one must have Python and PIP, preinstalled on their system. If Python and pip are already installed type the below command in the terminal.

pip3 install mysql-connector-python

Note: If Python is not present, go through How to install Python on Windows and Linux? and follow the instructions provided.

python mysql connector install

Connecting to MySQL Server

We can connect to the MySQL server using the connect() method. 

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password"
)
 
print(dataBase)
  
# Disconnecting from the server
dataBase.close()


Output:

<mysql.connector.connection_cext.CMySQLConnection object at 0x7f73f0191d00>

Note: For more information, refer to Connect MySQL database using MySQL-Connector Python.

Creating Database

After connecting to the MySQL server let’s see how to create a MySQL database using Python. For this, we will first create a cursor() object and will then pass the SQL command as a string to the execute() method. The SQL command to create a database is – 

CREATE DATABASE DATABASE_NAME

Example: Creating MySQL database with Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
 
# creating database
cursorObject.execute("CREATE DATABASE gfg")


Output:

Pyhton mysql create database

Creating Tables

For creating tables we will follow the similar approach of writing the SQL commands as strings and then passing it to the execute() method of the cursor object. SQL command for creating a table is – 

CREATE TABLE
(
    column_name_1 column_Data_type,
    column_name_2 column_Data_type,
    :
    :
    column_name_n column_Data_type
);

Example: Creating MySQL table using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
# creating table
studentRecord = """CREATE TABLE STUDENT (
                   NAME  VARCHAR(20) NOT NULL,
                   BRANCH VARCHAR(50),
                   ROLL INT NOT NULL,
                   SECTION VARCHAR(5),
                   AGE INT
                   )"""
  
# table created
cursorObject.execute(studentRecord)
  
# disconnecting from server
dataBase.close()


Output:

create table python mysql

Insert Data into Tables

To insert data into the MySQL table Insert into query is used. 

Syntax:

 INSERT INTO table_name (column_names) VALUES (data)

Example 1: Inserting Single Row

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\
VALUES (%s, %s, %s, %s, %s)"
val = ("Ram", "CSE", "85", "B", "19")
   
cursorObject.execute(sql, val)
dataBase.commit()
   
# disconnecting from server
dataBase.close()


Output:

insert 1 row in mysql database using Python

Example 2: Inserting Multiple Rows

To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method.

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\
VALUES (%s, %s, %s, %s, %s)"
val = [("Nikhil", "CSE", "98", "A", "18"),
       ("Nisha", "CSE", "99", "A", "18"),
       ("Rohan", "MAE", "43", "B", "20"),
       ("Amit", "ECE", "24", "A", "21"),
       ("Anil", "MAE", "45", "B", "20"),
       ("Megha", "ECE", "55", "A", "22"),
       ("Sita", "CSE", "95", "A", "19")]
   
cursorObject.executemany(sql, val)
dataBase.commit()
   
# disconnecting from server
dataBase.close()


Output:

python mysql insert many rows

Fetching Data

We can use the select query on the MySQL tables in the following ways –

  • In order to select particular attribute columns from a table, we write the attribute names.
SELECT attr1, attr2 FROM table_name
  • In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.
SELECT * FROM table_name

Example: Select data from MySQL table using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query = "SELECT NAME, ROLL FROM STUDENT"
cursorObject.execute(query)
   
myresult = cursorObject.fetchall()
   
for x in myresult:
    print(x)
 
# disconnecting from server
dataBase.close()


Output:

python mysql select query

Where Clause

Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.

Syntax:

SELECT column1, column2, â€Ķ. columnN FROM [TABLE NAME] WHERE [CONDITION];

Example: Where clause in MySQL using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query = "SELECT * FROM STUDENT where AGE >=20"
cursorObject.execute(query)
   
myresult = cursorObject.fetchall()
   
for x in myresult:
    print(x)
 
# disconnecting from server
dataBase.close()


Output:

('Rohan', 'MAE', 43, 'B', 20)
('Amit', 'ECE', 24, 'A', 21)
('Anil', 'MAE', 45, 'B', 20)
('Megha', 'ECE', 55, 'A', 22)

Order By Clause

OrderBy is used to arrange the result set in either ascending or descending order. By default, it is always in ascending order unless “DESC” is mentioned, which arranges it in descending order. “ASC” can also be used to explicitly arrange it in ascending order. But, it is generally not done this way since default already does that.

Syntax:

SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;

Example: Order By clause in MySQL using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query = "SELECT * FROM STUDENT ORDER BY NAME DESC"
cursorObject.execute(query)
   
myresult = cursorObject.fetchall()
   
for x in myresult:
    print(x)
 
# disconnecting from server
dataBase.close()


Output:

python mysql ordery by

Limit Clause

The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows.

Syntax:

SELECT * FROM tablename LIMIT limit;
SELECT * FROM tablename LIMIT limit OFFSET offset;

Example: Limit Clause in MySQL using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query = "SELECT * FROM STUDENT LIMIT 2 OFFSET 1"
cursorObject.execute(query)
   
myresult = cursorObject.fetchall()
   
for x in myresult:
    print(x)
 
# disconnecting from server
dataBase.close()


Output:

('Nikhil', 'CSE', 98, 'A', 18)
('Nisha', 'CSE', 99, 'A', 18)

Update Data

The update query is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate.

Syntax:

UPDATE tablename
SET ="new value"
WHERE ="old value";

Example: Update MySQL table using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query = "UPDATE STUDENT SET AGE = 23 WHERE Name ='Ram'"
cursorObject.execute(query)
dataBase.commit()
 
# disconnecting from server
dataBase.close()


Output:

python mysql update table

Delete Data from Table

We can use the Delete query to delete data from the table in MySQL.

Syntax:

DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE

Example: Delete Data from MySQL table using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query = "DELETE FROM STUDENT WHERE NAME = 'Ram'"
cursorObject.execute(query)
dataBase.commit()
 
# disconnecting from server
dataBase.close()


Output:

python mySQL delete from table

Drop Tables

Drop command affects the structure of the table and not data. It is used to delete an already existing table. For cases where you are not sure if the table to be dropped exists or not DROP TABLE IF EXISTS command is used. Both cases will be dealt with in the following examples.

Syntax:

DROP TABLE tablename;
DROP TABLE IF EXISTS tablename;

At first, let’s see the list of tables in our database.

python mysql drop tables

We can see that there are two tables for students, so let’s drop the second table.

Example 1: Drop Table in MySQL using Python

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query ="DROP TABLE Student;"
 
cursorObject.execute(query)
dataBase.commit()
 
# disconnecting from server
dataBase.close()


Output:

python mysql drop tables

Example 2: Drop Table if exists

Python3




# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="password",
  database = "gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
  
query ="Drop Table if exists Employee;"
 
cursorObject.execute(query)
dataBase.commit()
 
# disconnecting from server
dataBase.close()


The above example, will not create any error and output because we have used the Drop Table is exists query. If we will simply use the Drop table Employee then ProgrammingError: 1051 (42S02): Unknown table ‘gfg.Employee’ is raised.

Python MySQL Exercises

Working With Tables

Working on Columns

Python MySQL Applications and Projects



Similar Reads

Connect MySQL database using MySQL-Connector Python
While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Pytho
2 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python MySQL - Order By Clause
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause OrderBy is used to arrange the result set in either ascending or descendi
2 min read
Connect to MySQL using PyMySQL in Python
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database. What is PyMySQL? This package contains a pure-Python MySQL client library, based on PEP 249. Requirements : MySQL Server – one of the following : MySQL >= 5.5Maria
2 min read
How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python?
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the Minimum and Maximum Value of a Column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an
2 min read
Python MySQL - Create Database
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To conne
2 min read
Python MySQL - Select Query
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mySQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To conn
2 min read
Python: MySQL Create Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command.Installation Follow the below-men
3 min read
Python MySQL - Where Clause
Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.Syntax SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION]; The above syntax is used for displaying a certain set of data following the condit
2 min read
Python MySQL - Insert into Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. Note: Before we insert data into
3 min read
Python MySQL - Drop Table
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Drop Table Command Drop command affects the structure of the table and not data. It is u
2 min read
Python MySQL - Update Query
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Update Clause The update is used to change the existing values in a database. By using u
2 min read
Python MySQL - Join
A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Python-MySQL-Connector This is a MySQL Connector that allows Python to access MySQL Driv
2 min read
Python MySQL - Limit Clause
A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. Python-MySQL-Connector This is a MySQL Connector that allows Python to access MySQL Driver a
2 min read
How to install MySQL connector package in Python?
Prerequisite: Python Language Introduction MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. A connector is employed when we have to use MySQL with other programmin
2 min read
Create MySQL Database Login Page in Python using Tkinter
Prerequisites: Python GUI – tkinter, Python MySQL – Select QueryTkinter is one of the Python libraries which contains many functions for the development of graphic user interface pages and windows. Login pages are important for the development of any kind of mobile or web application. This page is most essential for user authentication purposes.We
2 min read
Profile Application using Python Flask and MySQL
A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not re
10 min read
Extract Data from Database using MySQL-Connector and XAMPP in Python
Prerequisites: MySQL-Connector, XAMPP Installation A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. RequirementsXAMPP: Database / Server
2 min read
How to Count the Number of Rows in a MySQL Table in Python?
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such a
2 min read
How to Print Out All Rows of a MySQL Table in Python?
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server(here XAMPP) we use various modules in P
2 min read
How to Copy a Table in MySQL Using Python?
In this article, we will create a table in MySQL and will create a copy of that table using Python. We will copy the entire table, including all the columns and the definition of the columns, as well as all rows of data in the table. To connect to MySQL database using python, we need PyMySql module. The cursor class allows python to execute SQL com
3 min read
How to Compute the Average of a Column of a MySQL Table Using Python?
A MySQL connector is needed to generate a connection between Python and the MySQL server. Here we will import mysql.connector library to get the average of the specified column in the given database. If you need to know how to install MySQL, see How to Install MySQL in Python 3. Average Function of SQL SQL AVG() function returns the average of valu
2 min read
Grant MySQL table and column permissions using Python
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such a
2 min read
How to Compute the Sum of All Rows of a Column of a MySQL Table Using Python?
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such a
2 min read
How to Perform Arithmetic Across Columns of a MySQL Table Using Python?
Python is a dynamic language, and Python applications can be integrated with database servers. The module used to access a MySQL database from Python is MySQL Connector Python. PyMySQL, MySQLDB and mysqlclient are other Python modules to communicate with a MySQL database server in Python. However, we will use MySQL Connector Python in this article
5 min read
How to Add a Column to a MySQL Table in Python?
Prerequisite: Python: MySQL Create Table Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. ALTER statement of SQL With the ALTER statement, one can add, drop
4 min read
How to Rename a MySQL Table in Python?
MySQL Connector-Python module is an API in python used to communicate with a MySQL database server. It only requires the standard Python libraries and has no additional dependencies. There are various other modules in Python like PyMySQL and mysqlclient which can be used to access a database server. In this article, we will use MySQL Connector-Pyth
3 min read
Get the id after INSERT into MySQL database using Python
Prerequisites: MySQL, mysql-connector for python The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to M
2 min read
How to Copy a Table Definition in MySQL Using Python?
Python requires an interface to access a database server. Python supports a wide range of interfaces to interact with various databases. To communicate with a MySQL database, MySQL Connector Python module, an API written purely in Python, is used. This module is self-sufficient meaning that it does not have dependencies and only requires the standa
6 min read
Add comment to column in MySQL using Python
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such a
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg