MySQL Database Database Connectivity in Python


A PROGRAM THAT ILLUSTRATES MYSQL DATABASE CONNECTION


Source Code

from tabulate import tabulate
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root", password="root", database="python_db")


def insert(name, age, city):
    res = con.cursor()
    sql = "insert into users (name,age,city) values (%s,%s,%s)"
    user = (name, age, city)
    res.execute(sql, user)
    con.commit()
    print("Data Insert Success")


def update(name, age, city,id):
    res = con.cursor()
    sql = "update users set name=%s,age=%s,city=%s where id=%s"
    user = (name, age, city,id)
    res.execute(sql, user)
    con.commit()
    print("Data Update Success")



def select():
    res = con.cursor()
    sql = "SELECT ID,NAME,AGE,CITY from users"
    res.execute(sql)
    # result=res.fetchone()
    # result=res.fetchmany(2)
    result = res.fetchall()
    print(tabulate(result, headers=["ID", "NAME", "AGE", "CITY"]))


def delete(id):
    res = con.cursor()
    sql = "delete from users where id=%s"
    user = (id,)
    res.execute(sql, user)
    con.commit()
    print("Data Delete Success")



while True:
    print("1.Insert Data")
    print("2.Update Data")
    print("3.Select Data")
    print("4.Delete Data")
    print("5.Exit")
    choice = int(input("Enter Your Choice : "))
    if choice == 1:
        name = input("Enter Name : ")
        age = input("Enter Age : ")
        city = input("Enter City : ")
        insert(name, age, city)
    elif choice == 2:
        id = input("Enter The Id : ")
        name = input("Enter Name : ")
        age = input("Enter Age : ")
        city = input("Enter City : ")
        update(name, age, city,id)
    elif choice == 3:
        select()
    elif choice == 4:
        id = input("Enter The Id to Delete : ")
        delete(id)
    elif choice == 5:
        quit()
    else:
        print("Invalid Selection . Please Try Again !")
1.Insert Data
2.Update Data
3.Select Data
4.Delete Data
5.Exit
Enter Your Choice : 1
Enter Name : Priya
Enter Age : 21
Enter City : Hosur
Data Insert Success
1.Insert Data
2.Update Data
3.Select Data
4.Delete Data
5.Exit
Enter Your Choice : 2
Enter The Id : 1
Enter Name : Harish
Enter Age : 22
Enter City : Salem
Data Update Success
1.Insert Data
2.Update Data
3.Select Data
4.Delete Data
5.Exit
Enter Your Choice : 4
Enter The Id to Delete : 3
Data Delete Success
1.Insert Data
2.Update Data
3.Select Data
4.Delete Data
5.Exit
Enter Your Choice : 3
  ID  NAME      AGE  CITY
----  ------  -----  -------
   1  Harish     22  Salem
   2  Pooja      23  Chennai
   4  Ram        21  Namakkal
   6  Priya      21  Hosur
1.Insert Data
2.Update Data
3.Select Data
4.Delete Data
5.Exit
Enter Your Choice : 5

Process finished with exit code 0

To download raw file Click Here