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

Sql

import mysql.connector
mydb = mysql.connector.connect(
    host='localhost',
    user='root',
    password='Sambhav7!',
    database='db1'
)

def addrecord():
    cur=mydb.cursor()
    name = input('ENTER NAME OF THE BOOK:')
    price = input('ENTER THE PRICE OF THE BOOK')
    author = input('ENTER THE AUTHOR\'S NAME')
    query="INSERT INTO books VALUES('{}',{},'{}')".format(name,price,author)
    cur.execute(query)
    mydb.commit()

def deleterecord():
    found = 0
    cur=mydb.cursor()
    name = input('Enter the book\'s name: ')
    query = 'Select * from books Name'
    cur.execute(query)
    result = cur.fetchall()
    for i in result:
        if i[0] == name:
            query="DELETE FROM books WHERE Name=%s;"
            cur.execute(query , [name])
            mydb.commit()
            found = 1
            return True           
    if found == 0:
        print('Book not found, try creating a new one')
        return False   

def updaterecord():
    cond = deleterecord()
    if cond:
        addrecord()
def displayrecord():
    cur = mydb.cursor()
    query = 'Select * from books Name'
    cur.execute(query)
    result = cur.fetchall()
    for row in result:
        print(row)
   
while True:
    print('\nMenu \n1.Add Record\n2.Update Record\n3.Delete Record\n4.View
Records\n5.Exit(Press any other key)')
    num = int(input('Enter a number: '))
    if num == 1:
        addrecord()
    elif num == 2:
        updaterecord()
    elif num == 3:
        deleterecord()
    elif num == 4:
        displayrecord()
    else:
        break

You might also like