Open In App

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.



Requirements

pip install mysql-connector
pip install wheel

Step-by-step Approach:

Procedure to create a table in the database:



Procedure for writing Python program:

import mysql.connector

conn_object=mysql.connector.connect(hostname,username,password,database_name)

Here, you will need to pass server name, username, password, and database name)

cur_object=conn_object,cursor()
query=DDL/DML etc
cur_obj=execute(query)
cur_obj.close()
conn_obj.close()

Below is the complete Python program based on the above approach:




# import required modules
import mysql.connector
  
# create connection object
con = mysql.connector.connect(
  host="localhost", user="root",
  password="", database="GEEK")
  
# create cursor object
cursor = con.cursor()
  
# assign data query
query1 = "desc geeksdemo"
  
# executing cursor
cursor.execute(query1)
  
# display all records
table = cursor.fetchall()
  
# describe table
print('\n Table Description:')
for attr in table:
    print(attr)
  
# assign data query
query2 = "select * from geeksdemo"
  
# executing cursor
cursor.execute(query2)
  
# display all records
table = cursor.fetchall()
  
# fetch all columns
print('\n Table Data:')
for row in table:
    print(row[0], end=" ")
    print(row[1], end=" ")
    print(row[2], end=" ")
    print(row[3], end="\n")
      
# closing cursor connection
cursor.close()
  
# closing connection object
con.close()

Output:

Note: XAMPP Apache and MySQL should be kept on during the whole process. 


Article Tags :