Python MySQL – Retrieving data

MySQL is an open-source relational database management system. In this post we will be retrieving MySQL data via a Python script. You may also be interested in inserting data, updating data and deleting data.

The script expects two columns which are ‘Name’ and ‘Age’ to already exist as part of our database table. In this example we are assuming the users name and age already exist within the database, we will be using the name as input and reference to retrieve the users age.

Full source code for this project can be found below:

import mysql.connector
import time

def GetFromDB(Name):
    mydb = mysql.connector.connect(
    host="",
    user="",
    password="",
    database="")
    mycursor = mydb.cursor()
    mycursor.execute("SELECT Age FROM Table_1 WHERE Name ='"+Name+"'")
    myresult = mycursor.fetchone()
    for item in myresult:
        print("You are " + str(item) + " Years old")
    mycursor.close()
    mydb.close()
   

while 1 == 1:
    Name = input("Please Enter your Name: ")
    InsertToDB(Name)
    print("Thank you! Next person please\n\n")
    time.sleep(2)

Leave a Reply