flask、mysql、html更新数据表
时间: 2023-10-20 18:18:00 浏览: 36
要使用 Flask、MySQL 和 HTML 更新数据表,可以按照以下步骤进行操作:
1. 在 Flask 中编写路由函数,使用 GET 方法获取表单页面,使用 POST 方法提交表单数据。例如:
```python
from flask import Flask, render_template, request
import mysql.connector
app = Flask(__name__)
# 获取表单页面
@app.route('/update')
def update():
return render_template('update.html')
# 提交表单数据
@app.route('/update', methods=['POST'])
def update_post():
# 连接 MySQL 数据库
conn = mysql.connector.connect(user='username', password='password', database='database_name')
cursor = conn.cursor()
# 获取提交的表单数据
name = request.form['name']
age = request.form['age']
# 更新数据表
sql = "UPDATE user SET age=%s WHERE name=%s"
val = (age, name)
cursor.execute(sql, val)
conn.commit()
# 关闭数据库连接
cursor.close()
conn.close()
return '更新成功'
```
2. 编写 HTML 表单页面,使用 POST 方法提交表单数据。例如:
```html
<!DOCTYPE html>
<html>
<head>
<title>更新数据表</title>
</head>
<body>
<form method="POST" action="/update">
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br>
<label for="age">年龄:</label>
<input type="text" id="age" name="age"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
```
3. 启动 Flask 应用,访问 `/update` 路由,填写表单数据并提交即可更新数据表。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)