Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

MySQL

Connectivity
with Python
Quick Guide
1. Installation
2. PIP installation
3. Importing module
4. Connecting with MySQL database
5. Creating cursor instance
6. Executing Queries
7. Getting output in Python
8. Saving
Step 1 : Installation
Download and install
Python 3.7.2 and MySQL
5.1 on your computer
making sure that you
have enabled “ADD TO
PATH” check box while
installing both
Step 2 : PIP Installation
Open command prompt (your
system’s system client) and
type the following syntax
pip install mysql-connector
Step 3 : Importing module

Open a python file and


import the module by
typing the following
syntax:
import mysql.connector
Step 4 : Connecting to Database
After importing, establish a connectivity with your mysql
server from python by providing the host name, user name
and password by typing the following syntax:
<var>=mysql.connector.connect(host="localhost",user="<root
>",password="<root>"<,database=”<db>”>)
Step 5 : Creating
Cursor instance
After connecting to database,
check whether connection is
successful and create cursor
instance with the following
syntax.
Checking :
<db>.is_connected
Cursor :
<var>=<db>.connect
Step 6 : Executing Queries
Now you can execute queries
by using the following syntax:
<cursor>.execute(“<query>”)
Or
<var>=”<query>”
<cursor>.execute(var)
OR
Using variables in queries
There are 2 types of using variables
in queries:

➔ Old Style Format:


We use % as the variable and
then give the values in a tuple
after the query.

➔ New Style Format:


We use {} as the variable and
then give the values in a tuple
after .format after the query.
Old Style Format:

New Style Format:


Step 7 : Getting Output
After the select * command, use
<var>=<cursor>.[fetchall(),fetchone(),fetchmany(<n>)]
will generally give output in the form of tuples nested
in a list [(),(),()] .
In order to get separated rows, we use for loop.
for <i> in var:
print(i)
Step 8 : Saving
After every DDL statement make
sure you save it and make the
changes permanent by typing
the following syntax:
<db>.commit()
THANK
YOU

You might also like