python+mysql学生管理系统代码实现
时间: 2023-10-29 09:06:04 浏览: 79
以下是一个简单的Python+MySQL学生管理系统代码实现,包括添加、删除、修改和查询学生信息功能:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='123456', db='student')
# 创建游标
cursor = db.cursor()
# 添加学生信息
def add_student(name, age, gender, score):
sql = "INSERT INTO students(name, age, gender, score) VALUES ('%s', %d, '%s', %.2f)" % (name, age, gender, score)
try:
cursor.execute(sql)
db.commit()
print("添加学生信息成功!")
except:
db.rollback()
print("添加学生信息失败!")
# 删除学生信息
def delete_student(id):
sql = "DELETE FROM students WHERE id = %d" % id
try:
cursor.execute(sql)
db.commit()
print("删除学生信息成功!")
except:
db.rollback()
print("删除学生信息失败!")
# 修改学生信息
def update_student(id, name, age, gender, score):
sql = "UPDATE students SET name = '%s', age = %d, gender = '%s', score = %.2f WHERE id = %d" % (name, age, gender, score, id)
try:
cursor.execute(sql)
db.commit()
print("修改学生信息成功!")
except:
db.rollback()
print("修改学生信息失败!")
# 查询学生信息
def query_student(id):
sql = "SELECT * FROM students WHERE id = %d" % id
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print("ID:%d, 姓名:%s, 年龄:%d, 性别:%s, 成绩:%.2f" % (row[0], row[1], row[2], row[3], row[4]))
except:
print("查询学生信息失败!")
# 关闭数据库连接
def close_db():
db.close()
# 测试代码
if __name__ == "__main__":
print("1. 添加学生信息")
print("2. 删除学生信息")
print("3. 修改学生信息")
print("4. 查询学生信息")
print("5. 退出程序")
while True:
choice = int(input("请输入要执行的操作:"))
if choice == 1:
name = input("请输入学生姓名:")
age = int(input("请输入学生年龄:"))
gender = input("请输入学生性别:")
score = float(input("请输入学生成绩:"))
add_student(name, age, gender, score)
elif choice == 2:
id = int(input("请输入要删除的学生ID:"))
delete_student(id)
elif choice == 3:
id = int(input("请输入要修改的学生ID:"))
name = input("请输入学生姓名:")
age = int(input("请输入学生年龄:"))
gender = input("请输入学生性别:")
score = float(input("请输入学生成绩:"))
update_student(id, name, age, gender, score)
elif choice == 4:
id = int(input("请输入要查询的学生ID:"))
query_student(id)
elif choice == 5:
close_db()
break
else:
print("输入有误,请重新输入!")
```
注意:在运行代码之前需要先创建一个名为`student`的MySQL数据库,并在其中创建一个名为`students`的表,表结构如下:
```sql
CREATE TABLE students (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT(11) NOT NULL,
gender VARCHAR(10) NOT NULL,
score FLOAT(2) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
阅读全文