Python Flask SQLite 增删改查示例
这是一个使用Python的Flask框架和SQLite数据库实现增删改查功能的示例。
首先,需要安装Flask和SQLite库:
pip install Flask
pip install sqlite3
接下来,创建一个app.py文件,代码如下:
from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
@app.route('/')
def index():
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
conn.commit()
c.execute('SELECT * FROM users')
users = c.fetchall()
conn.close()
return render_template('index.html', users=users)
@app.route('/add', methods=['POST'])
def add():
name = request.form['name']
age = request.form['age']
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('INSERT INTO users (name, age) VALUES (?, ?)', (name, age))
conn.commit()
conn.close()
return redirect(url_for('index'))
@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
if request.method == 'POST':
name = request.form['name']
age = request.form['age']
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('UPDATE users SET name = ?, age = ? WHERE id = ?', (name, age, id))
conn.commit()
conn.close()
return redirect(url_for('index'))
else:
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('SELECT * FROM users WHERE id = ?', (id,))
user = c.fetchone()
conn.close()
return render_template('edit.html', user=user)
@app.route('/delete/<int:id>')
def delete(id):
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('DELETE FROM users WHERE id = ?', (id,))
conn.commit()
conn.close()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
这段代码定义了四个路由:
其中,'/'路由会查询所有用户信息,并使用render_template方法渲染index.html模板。代码中的data.db是SQLite数据库文件,保存在当前工作目录下。
然后,创建两个HTML模板文件index.html和edit.html,代码如下:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>用户信息</title>
</head>
<body>
<h1>用户信息</h1>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
{% for user in users %}
<tr>
<td>{{ user[1] }}</td>
<td>{{ user[2] }}</td>
<td>
<a href='/edit/{{ user[0] }}'>编辑</a>
<a href='/delete/{{ user[0] }}'>删除</a>
</td>
</tr>
{% endfor %}
</table>
<h2>添加用户</h2>
<form method='post' action='/add'>
<label for='name'>姓名:</label>
<input type='text' name='name' required>
<label for='age'>年龄:</label>
<input type='number' name='age' required>
<button type='submit'>添加</button>
</form>
</body>
</html>
edit.html:
<!DOCTYPE html>
<html>
<head>
<title>编辑用户信息</title>
</head>
<body>
<h1>编辑用户信息</h1>
<form method='post' action=''>
<label for='name'>姓名:</label>
<input type='text' name='name' value='{{ user[1] }}' required>
<label for='age'>年龄:</label>
<input type='number' name='age' value='{{ user[2] }}' required>
<button type='submit'>保存</button>
</form>
</body>
</html>
这两个模板文件使用了Flask的模板语言,可以根据需要进行修改。
最后,运行app.py文件,访问http://localhost:5000即可看到效果。
原文地址: https://www.cveoy.top/t/topic/mQeD 著作权归作者所有。请勿转载和采集!