用python嵌套mysql语言编写一个学生管理系统
时间: 2023-07-18 15:33:43 浏览: 109
好的,以下是一个简单的学生管理系统的Python代码,使用MySQL作为数据库:
```python
import mysql.connector
# 连接数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="students"
)
# 创建游标
cursor = db.cursor()
# 创建学生表
cursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT, gender VARCHAR(255), grade VARCHAR(255))")
# 插入学生信息
def insert_student(name, age, gender, grade):
sql = "INSERT INTO students (name, age, gender, grade) VALUES (%s, %s, %s, %s)"
val = (name, age, gender, grade)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "记录插入成功!")
# 更新学生信息
def update_student(id, name, age, gender, grade):
sql = "UPDATE students SET name = %s, age = %s, gender = %s, grade = %s WHERE id = %s"
val = (name, age, gender, grade, id)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "记录更新成功!")
# 删除学生信息
def delete_student(id):
sql = "DELETE FROM students WHERE id = %s"
val = (id, )
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "记录删除成功!")
# 查询学生信息
def get_students():
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()
for student in students:
print(student)
# 测试
insert_student("张三", 18, "男", "一年级")
insert_student("李四", 19, "女", "二年级")
update_student(1, "张三三", 19, "女", "二年级")
delete_student(2)
get_students()
# 关闭数据库连接
db.close()
```
这段代码包括了创建学生表、插入、更新、删除、查询学生信息等基本操作。你可以根据自己的需求进行修改和扩展。
阅读全文