如何在Python Flask中实现一键执行多段SQL脚本
实现Flask按钮触发PostgreSQL的插入/更新/查询操作
1. 配置Flask与数据库连接
先通过SQLAlchemy完成数据库基础连接配置,替换成你的PostgreSQL真实信息:
from flask import Flask, render_template, request from sqlalchemy import create_engine, text app = Flask(__name__) # PostgreSQL连接格式:postgresql://用户名:密码@主机:端口/数据库名 engine = create_engine('postgresql://your_user:your_pwd@localhost:5432/your_database')
2. 编写处理数据库操作的路由
创建一个POST路由,用来接收按钮的触发请求,按顺序执行插入、更新、查询逻辑:
@app.route('/run-db-ops', methods=['POST']) def run_database_operations(): with engine.connect() as conn: # 1. 执行插入操作(替换成你验证过的SQL) conn.execute(text("INSERT INTO your_table (column1, column2) VALUES ('demo_val1', 'demo_val2')")) # 2. 执行更新操作 conn.execute(text("UPDATE your_table SET column2 = 'updated_val' WHERE column1 = 'demo_val1'")) # 3. 执行查询操作 query_result = conn.execute(text("SELECT * FROM your_table WHERE column1 = 'demo_val1'")) # 将查询结果转为字典列表,方便前端展示 records = [dict(row) for row in query_result] # 提交事务,确保写入操作生效 conn.commit() # 将结果传递给模板展示 return render_template('result.html', records=records) # 首页路由,展示触发按钮 @app.route('/') def index(): return render_template('index.html')
3. 前端页面添加触发按钮
在templates/index.html中添加表单,通过POST请求触发数据库操作路由:
<!DOCTYPE html> <html> <head> <title>DB操作触发</title> </head> <body> <form action="{{ url_for('run_database_operations') }}" method="POST"> <button type="submit">执行插入→更新→查询</button> </form> </body> </html>
4. 结果展示模板(可选)
创建templates/result.html展示查询结果:
<!DOCTYPE html> <html> <head> <title>操作结果</title> </head> <body> <h3>查询结果:</h3> {% for record in records %} <p>{{ record }}</p> {% endfor %} <a href="{{ url_for('index') }}">返回重新操作</a> </body> </html>
关键注意事项
- 必须用POST请求处理插入、更新这类写操作,避免GET请求的安全风险
- 执行写操作后务必调用
conn.commit(),否则修改不会持久化到数据库 - 推荐使用参数绑定避免SQL注入,示例:
conn.execute(text("INSERT INTO your_table (column1) VALUES (:val)"), {"val": "safe_value"})
内容的提问来源于stack exchange,提问作者Yuju Takahashi
相关产品推荐
相关产品推荐

