Merhaba,
mysql de oluşturduğum studentinfo adlı bir tablo var. Tablo içerisindeki columnlardan bilgi çekmek istediğimde class altına (host user gibi bilgileri tekrar def getStudents in altına almadan) getirmeye çalıştığımda, getStudents tanımlı değil şeklinde hata alıyorum. Class altına bu kodu nasıl alabiliirm. Ayrıca birthdate i almak istediğimde datetime.datetime is not subscritaple şeklinde hata aldım. Bunu stringe mi çevirmelyim nasıl çözebilirim.
import mysql.connector
import datetime
mydb = mysql.connector.connect (
host = "localhost",
user = "root",
password = "1453",
database = "studentapplication",
)
class Student:
mydb = mydb
mycursor = mydb.cursor()
def __init__(self, studentNumber, name, surname, birthdate, gender):
self.studentNumber = studentNumber
self.name = name
self.surname = surname
self.birthdate = birthdate
self.gender = gender
def saveStudent(self):
sql = 'INSERT INTO studentinfo (studentNumber,Name, Surname, Birthdate, Gender) VALUES (%s,%s,%s,%s,%s)'
value = (self.studentNumber,self.name, self.surname, self.birthdate, self.gender)
Student.mycursor.execute(sql, value)
try:
mydb.commit()
print(f' Made {Student.mycursor.rowcount} operations.')
except mysql.connector.Error as err:
print('error:' , err)
finally:
Student.mydb.close()
@staticmethod
def saveStudents(students):
sql = 'INSERT INTO studentinfo (studentNumber,Name, Surname, Birthdate, Gender) VALUES (%s,%s,%s,%s,%s)'
values = students
Student.mycursor.executemany(sql, values)
try:
mydb.commit()
print(f' Made {Student.mycursor.rowcount} operations.')
except mysql.connector.Error as err:
print('error:' , err)
finally:
Student.mydb.close()
# new = Student('1044','Michael', 'Kors', datetime.datetime(1999, 4, 25),'M' )
# new.saveStudent()
students = [
('105','Leydi', 'Pink', datetime.datetime(2001, 5, 10),'F' ),
]
# mycursor.executemany(sql, students )
# Student.saveStudents(students)
def getStudents():
mydb = mysql.connector.connect (host = "localhost",user = "root", password = "1453",database = "studentapplication")
mycursor = mydb.cursor()
mycursor.execute('SELECT name, birthdate FROM studentinfo')
result = mycursor.fetchone()
for info in result:
print(f'name: {info[0]} birthdate: {info[1]}')
getStudents()