python flask 数据库查找某条记录前后5条记录
以下是一个示例代码,使用Python Flask和SQLite数据库来查找某条记录前后的五条记录。
from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
@app.route('/')
def index():
# 连接到SQLite数据库
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
# 查询指定记录的前后五条记录
record_id = 10 # 假设要查找的记录ID为10
query = "SELECT * FROM your_table WHERE id >= ? ORDER BY id ASC LIMIT 6"
cursor.execute(query, (record_id - 5,))
# 获取查询结果
records = cursor.fetchall()
# 关闭数据库连接
cursor.close()
conn.close()
# 渲染模板并传递查询结果给模板
return render_template('index.html', records=records)
if __name__ == '__main__':
app.run()
在上面的示例代码中,需要将your_database.db和your_table替换为实际的数据库文件和表名称。
在模板文件index.html中,可以使用Jinja2模板语言来循环遍历查询结果并显示。
<!DOCTYPE html>
<html>
<head>
<title>Records</title>
</head>
<body>
<h1>Records</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Value</th>
</tr>
{% for record in records %}
<tr>
<td>{{ record[0] }}</td>
<td>{{ record[1] }}</td>
<td>{{ record[2] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
在上面的示例中,查询结果的record变量是一个包含ID、名称和值的元组。你可以根据实际情况来调整模板中的表格结构和显示内容。
请注意,上述示例代码仅仅是一个简单的示例,实际使用时需要根据具体的需求进行适当的修改和完善
原文地址: http://www.cveoy.top/t/topic/iZNU 著作权归作者所有。请勿转载和采集!