"""Example project for ouda."""
import mysql.connector
mysqldb = mysql.connector.connect(
host="localhost", user="root", password="password", database="ouda"
)
mycursor = mysqldb.cursor()
class Student:
"""main class for students"""
def __init__(self, name, mail_address, gender):
"""Create a object of the student class.
Parameters
----------
name: str
The name of the student
mail_address: str
The email address of the students
gender: gender accept values M or F
"""
self.student_id = 0
self.name = name
self.mail_address = mail_address
self.gender = gender
def __str__(self):
return " id: %s name: %s " % (self.student_id, self.name)
def get_student_id(self):
"""Return id from the student table for existing student object"""
sql = (
"SELECT student_id FROM student WHERE name='%s' AND mail_address='%s' AND gender='%s'"
% (self.name, self.mail_address, self.gender)
)
print(sql)
mycursor.execute(sql)
return mycursor.fetchone()[0]
def save(self):
if self.student_id == 0:
# we have not saved a student yet
sql = (
"""INSERT INTO student (name, mail_address, gender) VALUES('%s', '%s', '%s')"""
% (self.name, self.mail_address, self.gender)
)
else:
# Record is presend already we need to update it only.
sql = """UPDATE student SET name=%s WHERE student_id="%s" """ % (
self.name,
self.student_id,
)
print(sql)
mycursor.execute(sql)
mysqldb.commit()
self.student_id = self.get_student_id()
def studentlist():
"""Return existing student list."""
sql = """SELECT * from student"""
mycursor.execute(sql)
recordlist = mycursor.fetchall()
StudentList = []
for student in recordlist:
studentobj = Student(student[1], student[2], student[3])
studentobj.student_id = student[0]
StudentList.append(studentobj)
return StudentList
def main():
"""Show simple sorting."""
for student in studentlist():
print(student)
newstudent = Student("Mike", "[email protected]", "M")
newstudent.save()
if __name__ == "__main__":
main()
Comments