学生管理系统python+mysql
时间: 2023-11-30 21:43:25 浏览: 96
以下是一个简单的学生管理系统的Python+MySQL实现,包括学生信息的添加、查询、修改和删除功能:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='students')
# 创建游标对象
cursor = db.cursor()
# 添加学生信息
def add_student(name, age, gender):
sql = "INSERT INTO student(name, age, gender) VALUES('%s', '%d', '%s')" % (name, age, gender)
try:
cursor.execute(sql)
db.commit()
print("添加成功!")
except:
db.rollback()
print("添加失败!")
# 查询学生信息
def query_student(name):
sql = "SELECT * FROM student WHERE name='%s'" % name
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
age = row[2]
gender = row[3]
print("ID:%d,姓名:%s,年龄:%d,性别:%s" % (id, name, age, gender))
except:
print("查询失败!")
# 修改学生信息
def update_student(id, name, age, gender):
sql = "UPDATE student SET name='%s', age='%d', gender='%s' WHERE id='%d'" % (name, age, gender, id)
try:
cursor.execute(sql)
db.commit()
print("修改成功!")
except:
db.rollback()
print("修改失败!")
# 删除学生信息
def delete_student(id):
sql = "DELETE FROM student WHERE id='%d'" % id
try:
cursor.execute(sql)
db.commit()
print("删除成功!")
except:
db.rollback()
print("删除失败!")
# 关闭数据库连接
db.close()
```
阅读全文