用sqlite3,flask和python写一个数据库信息管理系统,要求能运行
时间: 2024-02-13 07:04:04 浏览: 159
好的,下面是一个简单的数据库信息管理系统的 Python 代码,使用 Flask 和 SQLite3 数据库。请按照以下步骤进行操作:
1. 安装 Flask 和 SQLite3:
```
pip install flask
pip install sqlite3
```
2. 创建一个名为 `app.py` 的 Python 文件,将以下代码复制并粘贴到文件中:
```python
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
# 创建数据库
conn = sqlite3.connect('database.db')
print("Opened database successfully")
# 创建数据表
conn.execute('CREATE TABLE IF NOT EXISTS students (name TEXT, email TEXT, address TEXT)')
print("Table created successfully")
conn.close()
@app.route('/')
def home():
return render_template('home.html')
# 添加学生信息
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/addrecord', methods=['POST'])
def addrecord():
if request.method == 'POST':
try:
name = request.form['name']
email = request.form['email']
address = request.form['address']
# 插入数据
with sqlite3.connect("database.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO students (name, email, address) VALUES (?, ?, ?)", (name, email, address))
con.commit()
msg = "Record successfully added"
except:
con.rollback()
msg = "Error occurred"
finally:
con.close()
return render_template("result.html", msg=msg)
# 显示学生信息
@app.route('/view')
def view():
con = sqlite3.connect("database.db")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("SELECT * FROM students")
rows = cur.fetchall()
return render_template("view.html", rows=rows)
if __name__ == '__main__':
app.run(debug=True)
```
3. 创建名为 `templates` 的文件夹,并在其中创建以下四个 HTML 文件:
- `home.html`:主页面
```html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Database Information Management System</h1>
<p><a href="/add">Add Student Information</a></p>
<p><a href="/view">View Student Information</a></p>
</body>
</html>
```
- `add.html`:添加页面
```html
<!DOCTYPE html>
<html>
<head>
<title>Add Student Information</title>
</head>
<body>
<h1>Add Student Information</h1>
<form method="post" action="/addrecord">
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Address: <input type="text" name="address"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
```
- `view.html`:查看页面
```html
<!DOCTYPE html>
<html>
<head>
<title>View Student Information</title>
</head>
<body>
<h1>View Student Information</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{ row['name'] }}</td>
<td>{{ row['email'] }}</td>
<td>{{ row['address'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
```
- `result.html`:结果页面
```html
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<h1>{{ msg }}</h1>
<p><a href="/">Back to Home</a></p>
</body>
</html>
```
4. 运行 `app.py` 文件,并在浏览器中打开 `http://localhost:5000` 查看运行结果。
需要注意的是,在实际开发中,需要对输入的数据进行验证和清理,以避免 SQL 注入等风险。
阅读全文