如何使用Python从SQLite3数据库拉取姓名并在网页上修改?
实现Python从SQLite3拉取姓名数据并在网页修改的方案
1. 准备SQLite数据库与测试数据
先创建包含姓名的数据库表,并插入测试数据:
import sqlite3 # 连接或创建SQLite数据库文件 conn = sqlite3.connect('names.db') cursor = conn.cursor() # 创建姓名表(不存在则创建) cursor.execute(''' CREATE TABLE IF NOT EXISTS names ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL ) ''') # 插入3条测试姓名数据 cursor.execute("INSERT INTO names (name) VALUES ('张三'), ('李四'), ('王五')") conn.commit() conn.close()
2. 用Flask搭建Web服务(后端逻辑)
Flask是轻量型Web框架,适合快速实现这个需求。先安装依赖:
pip install flask
创建app.py作为后端核心文件:
from flask import Flask, render_template, request, redirect, url_for import sqlite3 app = Flask(__name__) # 从数据库拉取所有姓名数据 def fetch_all_names(): conn = sqlite3.connect('names.db') cursor = conn.cursor() cursor.execute('SELECT id, name FROM names') names = cursor.fetchall() # 返回格式:[(id1, name1), (id2, name2)...] conn.close() return names # 更新指定ID的姓名 def update_name_by_id(name_id, new_name): conn = sqlite3.connect('names.db') cursor = conn.cursor() # 使用参数化查询避免SQL注入 cursor.execute('UPDATE names SET name = ? WHERE id = ?', (new_name, name_id)) conn.commit() conn.close() # 首页路由:展示所有姓名 @app.route('/') def index(): names_list = fetch_all_names() return render_template('index.html', names=names_list) # 修改姓名的路由:处理POST请求 @app.route('/update/<int:id>', methods=['POST']) def update(id): new_name = request.form.get('new_name').strip() if new_name: update_name_by_id(id, new_name) return redirect(url_for('index')) # 重定向回首页刷新数据 if __name__ == '__main__': app.run(debug=True) # 开发模式运行,修改代码自动重启
3. 前端页面实现(展示与修改)
在项目根目录创建templates文件夹(Flask默认模板路径),并创建index.html:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>姓名管理工具</title> <style> .name-card { margin: 15px 0; padding: 12px; border: 1px solid #eee; width: 350px; border-radius: 4px; } input[type="text"] { padding: 6px; width: 220px; margin: 0 8px; border: 1px solid #ddd; border-radius: 3px; } button { padding: 6px 12px; background: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer; } button:hover { background: #0056b3; } </style> </head> <body> <h2>姓名列表</h2> {% for name in names %} <div class="name-card"> <form method="POST" action="{{ url_for('update', id=name[0]) }}"> <span>ID: {{ name[0] }} | 当前姓名: {{ name[1] }}</span> <input type="text" name="new_name" placeholder="输入新姓名" required> <button type="submit">保存修改</button> </form> </div> {% endfor %} </body> </html>
4. 运行与使用
- 先运行创建数据库的脚本,生成
names.db文件 - 运行
app.py,终端会显示访问地址(默认是http://127.0.0.1:5000) - 在浏览器打开地址,就能看到所有姓名,每个姓名后可输入新值并点击修改,页面会自动刷新展示更新后的数据
内容的提问来源于stack exchange,提问作者RCanaway
相关产品推荐
相关产品推荐

