用python建立一个链接数据库的学生管理系统
时间: 2023-12-19 07:05:55 浏览: 72
好的,我可以帮你解答这个问题。
首先,你需要先安装 Python 的数据库 API,比如 MySQL Connector,它可以帮助 Python 与 MySQL 数据库进行通信。你可以通过 pip 安装:
```python
pip install mysql-connector-python
```
然后,你需要创建一个 MySQL 数据库,并在其中创建一个名为“students”的表,表结构可以如下:
```sql
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
gender VARCHAR(10),
grade FLOAT
);
```
接下来,你需要编写 Python 代码来实现学生管理系统的功能。下面是一个简单的示例:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 添加学生信息
def add_student(name, age, gender, grade):
sql = "INSERT INTO students (name, age, gender, grade) VALUES (%s, %s, %s, %s)"
val = (name, age, gender, grade)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
# 更新学生信息
def update_student(id, name=None, age=None, gender=None, grade=None):
sql = "UPDATE students SET "
val = []
if name:
sql += "name=%s, "
val.append(name)
if age:
sql += "age=%s, "
val.append(age)
if gender:
sql += "gender=%s, "
val.append(gender)
if grade:
sql += "grade=%s, "
val.append(grade)
sql = sql[:-2] + " WHERE id=%s"
val.append(id)
mycursor.execute(sql, tuple(val))
mydb.commit()
print(mycursor.rowcount, "record(s) affected.")
# 删除学生信息
def delete_student(id):
sql = "DELETE FROM students WHERE id=%s"
val = (id,)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted.")
# 查询学生信息
def query_student(id=None):
sql = "SELECT * FROM students"
if id:
sql += " WHERE id=%s"
val = (id,)
mycursor.execute(sql, val)
else:
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
print(row)
# 测试
add_student("Tom", 18, "male", 80.5)
add_student("Alice", 19, "female", 90.0)
update_student(1, grade=85.0)
delete_student(2)
query_student()
```
这段代码实现了添加、更新、删除和查询学生信息的功能。你可以根据需要进行修改和扩展。
阅读全文