python学生成绩管理系统数据库代码-python+mysql实现学生信息查询系统
时间: 2024-02-04 12:04:27 浏览: 106
这是一个简单的 Python + MySQL 实现学生成绩管理系统的代码示例:
```python
import mysql.connector
# 连接 MySQL 数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 定义学生类
class Student:
def __init__(self, id, name, age):
self.id = id
self.name = name
self.age = age
# 添加学生信息到数据库
def add_student(student):
mycursor = mydb.cursor()
sql = "INSERT INTO students (id, name, age) VALUES (%s, %s, %s)"
val = (student.id, student.name, student.age)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
# 查询学生信息
def get_student(id):
mycursor = mydb.cursor()
sql = "SELECT * FROM students WHERE id = %s"
val = (id,)
mycursor.execute(sql, val)
result = mycursor.fetchone()
if result:
return Student(result[0], result[1], result[2])
else:
return None
# 更新学生信息
def update_student(id, name, age):
mycursor = mydb.cursor()
sql = "UPDATE students SET name = %s, age = %s WHERE id = %s"
val = (name, age, id)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected.")
# 删除学生信息
def delete_student(id):
mycursor = mydb.cursor()
sql = "DELETE FROM students WHERE id = %s"
val = (id,)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted.")
# 测试代码
student1 = Student(1, "Alice", 18)
student2 = Student(2, "Bob", 19)
add_student(student1)
add_student(student2)
print(get_student(1).name)
update_student(1, "Alex", 20)
print(get_student(1).name)
delete_student(2)
```
在上面的示例中,我们定义了一个 `Student` 类来表示学生信息,然后实现了添加、查询、更新和删除学生信息的函数。这些函数都是通过 MySQL 数据库来实现的。在测试代码中,我们添加了两个学生信息,然后查询和更新一个学生信息,最后删除一个学生信息。
阅读全文