Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/python3
# Import statements for libraries
import time
import MySQLdb
# Variable placeholders
Done = False
def new_student():
# Function for getting inputs from user for new student
roll_no=int(input("Enter New Roll No : "))
name = input("Enter New Student Name : ")
marks = int(input("Enter Marks : "))
return (roll_no, name, marks)
def user_input():
# Function to print a user menu
print ('\n\n')
print (30 * '-')
print (" M A I N - M E N U")
print (30 * '-')
print ('1. List Students')
print ('2. Add Student')
print ('3. Modify Student')
print ('4. Remove Student')
print ('x. Exit')
print (30 * '-')
#print('Enter You Choice')
choice = input('Enter Selection [1-4, x] : ')
print ("You entered", choice)
return choice
if __name__=='__main__':
# Create a connection to the database
db = MySQLdb.connect("localhost", "etec224", "password", "exampledb")
curs=db.cursor()
# Loop till user decides to exit
while Done != True:
# Get User input and save to the variable selection
selection = user_input()
if selection == 'x':
Done = True
else:
try:
selection = int(selection)
except:
print('Invalid input')
if selection == 1:
print('Listing Student')
try:
curs.execute("""SELECT * from STUDENT""")
for data in curs.fetchall():
print (str(data[0]) + "\t" + str(data[1]) + "\t" + str(data[2]))
db.commit()
except:
print("Error running query")
db.rollback()
elif selection == 2:
print('Adding Student')
try:
data_tuple = new_student()
curs.execute("""INSERT INTO STUDENT (ROLLNO, NAME, TOTAL_MARKS) VALUES(%s, %s, %s)""", data_tuple)
db.commit()
except:
print("Error running Query")
db.rollback()
elif selection == 3:
print('Modifying student')
try:
rn = input("Roll No of Student to edit : ")
marks = input("Enter New Marks : ")
curs.execute("""UPDATE STUDENT SET TOTAL_MARKS=%s WHERE ROLLNO=%s""", (marks, rn))
db.commit()
except:
print('Error running UPDATE Query')
db.rollback()
elif selection == 4:
print('Deleting Student')
try:
rn = input("Enter Roll No to delete : ")
curs.execute("""DELETE FROM STUDENT WHERE ROLLNO=%s """, (rn))
db.commit()
except:
print("Error Running DELETE query.")
db.rollback()
else:
print('Unrecognized Option. Try Again.')
time.sleep(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment