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
Connecting to MySQL Server
We can connect to the MySQL server using the connect() method.
# importing required libraries
import mysql.connector
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)
print(dataBase)
# Disconnecting from the server
dataBase.close()
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
# 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:
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 –
Example: Creating MySQL table using Python
# 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()
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
# 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()
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.
# 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()
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
# 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()