这个问题是关于如何用Python和web和MySQL创建学生信息管理系统的。
时间: 2024-03-06 10:48:02 浏览: 15
好的,你可以使用Python的Flask框架来搭建Web应用程序,并使用MySQL数据库来存储和管理学生信息。以下是一个示例代码,用于创建一个简单的学生信息管理系统:
1. 安装必要的依赖
```
pip install flask
pip install flask-mysqldb
```
2. 创建Flask应用程序并连接MySQL数据库
```
from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL
app = Flask(__name__)
# 配置MySQL数据库连接信息
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'test'
# 创建MySQL对象
mysql = MySQL(app)
```
3. 创建路由和视图函数
```
# 首页路由和视图函数
@app.route('/')
def index():
# 查询所有学生信息
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM students")
students = cur.fetchall()
cur.close()
return render_template('index.html', students=students)
# 添加学生路由和视图函数
@app.route('/add_student', methods=['GET', 'POST'])
def add_student():
if request.method == 'POST':
# 获取表单提交的学生信息
name = request.form['name']
age = request.form['age']
gender = request.form['gender']
grade = request.form['grade']
# 插入数据到数据库
cur = mysql.connection.cursor()
cur.execute("INSERT INTO students (name, age, gender, grade) VALUES (%s, %s, %s, %s)", (name, age, gender, grade))
mysql.connection.commit()
cur.close()
return redirect(url_for('index'))
return render_template('add_student.html')
# 删除学生路由和视图函数
@app.route('/delete_student/<int:id>')
def delete_student(id):
# 删除指定id的学生信息
cur = mysql.connection.cursor()
cur.execute("DELETE FROM students WHERE id=%s", (id,))
mysql.connection.commit()
cur.close()
return redirect(url_for('index'))
```
4. 创建HTML模板文件
```
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>学生信息管理系统</title>
</head>
<body>
<h1>学生信息列表</h1>
<table>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>年级</th>
<th>操作</th>
</tr>
{% for student in students %}
<tr>
<td>{{ student[0] }}</td>
<td>{{ student[1] }}</td>
<td>{{ student[2] }}</td>
<td>{{ student[3] }}</td>
<td>{{ student[4] }}</td>
<td><a href="{{ url_for('delete_student', id=student[0]) }}">删除</a></td>
</tr>
{% endfor %}
</table>
<p><a href="{{ url_for('add_student') }}">添加学生</a></p>
</body>
</html>
<!-- add_student.html -->
<!DOCTYPE html>
<html>
<head>
<title>添加学生</title>
</head>
<body>
<h1>添加学生</h1>
<form method="POST" action="{{ url_for('add_student') }}">
<p>姓名:<input type="text" name="name"></p>
<p>年龄:<input type="text" name="age"></p>
<p>性别:<input type="radio" name="gender" value="male" checked>男<input type="radio" name="gender" value="female">女</p>
<p>年级:<input type="text" name="grade"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
```
这是一个简单的示例,你可以根据自己的需求更改路由和视图函数,以及HTML模板文件。希望这对你有所帮助!