使用按钮通过Flask运行SQL查询是一种常见的Web应用场景,可以通过以下步骤实现:
pip install flask
.from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/query', methods=['POST'])
def query():
query_text = request.form['query']
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute(query_text)
result = cursor.fetchall()
conn.close()
return render_template('result.html', result=result)
<!DOCTYPE html>
<html>
<head>
<title>SQL查询</title>
</head>
<body>
<h1>SQL查询</h1>
<form action="/query" method="post">
<textarea name="query" rows="5" cols="50"></textarea>
<br>
<input type="submit" value="运行查询">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>查询结果</title>
</head>
<body>
<h1>查询结果</h1>
<table>
{% for row in result %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>
export FLASK_APP=app.py
flask run
http://localhost:5000
,即可看到查询界面。在文本框中输入SQL查询语句,点击"运行查询"按钮,即可执行查询并显示结果。需要注意的是,上述示例中使用了SQLite数据库作为示例,实际应用中可以根据需要使用其他数据库,如MySQL、PostgreSQL等。另外,为了安全起见,应该对用户输入的查询语句进行合法性验证和防止SQL注入攻击的处理。
推荐的腾讯云相关产品:腾讯云数据库MySQL、腾讯云数据库PostgreSQL、腾讯云Serverless Cloud Function等。你可以在腾讯云官网上找到这些产品的详细介绍和文档。
腾讯云数据库MySQL:https://cloud.tencent.com/product/cdb 腾讯云数据库PostgreSQL:https://cloud.tencent.com/product/postgres 腾讯云Serverless Cloud Function:https://cloud.tencent.com/product/scf
领取专属 10元无门槛券
手把手带您无忧上云