以下将介绍Flask-SQLAlchemy对数据库增删改查的简单示例。
一、安装所需的库
pip install flask flask-sqlalchemy flask-mysql
二、创建数据表
本示例使用mysql创建数据库和表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
三、创建app.py文件
# -*- coding: UTF-8 -*-
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#以下root为mysql数据库账号,123456为密码,localhost为数据库地址,demodb为数据库名
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:123456@localhost/demodb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# 定义一个模型类:
class User(db.Model):
# 表的结构:
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
age = db.Column(db.Integer)
@app.route('/')
def hello_world():
return 'Hello World!'
# 插入一条记录:
@app.route('/add', methods=['POST'])
def add():
name = request.json['name']
age = request.json['age']
new_user = User(name=name, age=age)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User created successfully'})
# 查询所有记录:
@app.route('/query')
def query():
users = User.query.all()
msg=""
for user in users:
msg += str(user.id) + ":" + user.name+"."
print(msg)
return msg
# 更新一条记录:
@app.route('/update', methods=['POST'])
def update():
id = request.json['id']
user = User.query.get(id)
if user:
name = request.json['name'] if 'name' in request.json else user.name
age = request.json['age'] if 'age' in request.json else user.age
user.name = name
user.age = age
db.session.commit()
return jsonify({'message': 'User updated successfully'})
else:
return jsonify({'message': 'User not found'}), 404
# 删除一条记录:
@app.route('/delete', methods=['POST'])
def delete():
id = request.json['id']
user = User.query.get(id)
if user:
db.session.delete(user)
db.session.commit()
return jsonify({'message': 'User deleted successfully'})
else:
return jsonify({'message': 'User not found'}), 404
if __name__ == '__main__':
app.run(debug=True)
四、运行程序
运行程序后,以下使用postman工具模拟提交参数
1.添加数据
2.查询数据表
以上示例介绍完毕。