Connect MYSQL Database with python using Pymysql Package



In this article , i'll explain you ways to attach python backend with MySQL database , and retrieve all data from database .
Connect MYSQL Database with python using Pymysql Package




Steps for creating Database in Xampp :- 

1.Download Xampp from here :-https://www.apachefriends.org/index.html .
2.after install xampp start Apache and Mysql module .

control pannel of xampp


3.Goto the browser and type "localhost/phpmyadmin" at that time you'll redirect to those page :-

phpmyadmin for python database connectivity

  4.Click on new button Enter the name of Database that you simply want to create .
  5.Enter the name of the table and required number columns therein table .
  6.Enter the Attributes of table , select proper data type and enter the length and click on  on the "Save" button.

create database in xampp for python database connectivity using pymysql package

  7.Your empty database is formed successfully.

  8.Click on Insert button , insert 2-3 rows of random data.

You may also like:- Create your first API using 'Deno' and fetch all the data from API in the Flutter app using 'http' package !!!



Steps for creating Python Back-end :-

  1. First we want to install package i.e pymyql package.

installing pymysql package for python database connectivity

 2. For windows users goto the "cmd" run it as Administrator , Enter the command "pip install pymysql".
 3. After installing package you'll be ready to use that package in your application .
 4. pymysql package provides connect method which is employed for creating reference to database .
                               
     pymysql.connect(  host='localhost',user='root',password="",db="book")

Pymysql.connect method takes 4 parameters host="localhost" , user="root" ,password ="" and database name , here i kept the password  as null.you can change your password by visiting "Privileges" section.

change password for xampp database




Code :-

import pymysql

con=pymysql.connect(host='localhost',user='root',password="",db="book")

a=con.cursor()

sql="SELECT * FROM book ;"

a.execute(sql)

data=a.fetchall()

for row in data:
    print("name of book :",row[1],"\t author name :",row[2]," \t\t Department :",row[3])


In this above code we want to make cursor object . It gives us the flexibility to possess multiple seperate working environments through the identical connection to the database. you can create a cursor by executing the 'cursor' function with your database object like a = con.cursor().

1) fetchall() method will retrieve all data from from database .
2) fetchone() method will only retrieve the first (primary) record of the database.




Output :-
output of python database connectivity with pymysql package
output

Thank you guys for spending you valuable time in reading this article, if you have doubts please ask those doubts in comment section.