flask连接数据库实现增删改查
时间: 2023-10-27 15:08:05 浏览: 92
首先需要安装Flask和对应的数据库驱动,比如MySQL或者SQLite等。以MySQL为例,可以使用pymysql库来连接数据库。
在Flask中,可以使用Flask-SQLAlchemy来简化数据库操作。下面是一个示例代码,实现了对用户信息的增删改查操作:
```python
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# 配置数据库连接信息
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@localhost:3306/database_name'
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(50))
age = db.Column(db.Integer)
def __repr__(self):
return f'<User {self.id}: {self.name}, {self.age}>'
# 添加用户
@app.route('/users', methods=['POST'])
def add_user():
data = request.get_json()
user = User(name=data['name'], age=data['age'])
db.session.add(user)
db.session.commit()
return {'message': 'User added successfully'}
# 查询所有用户
@app.route('/users', methods=['GET'])
def get_all_users():
users = User.query.all()
return {'users': [user.__dict__ for user in users]}
# 查询单个用户
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = User.query.filter_by(id=user_id).first()
if user:
return user.__dict__
else:
return {'message': 'User not found'}
# 更新用户信息
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
user = User.query.filter_by(id=user_id).first()
if user:
data = request.get_json()
user.name = data['name']
user.age = data['age']
db.session.commit()
return {'message': 'User updated successfully'}
else:
return {'message': 'User not found'}
# 删除用户
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
user = User.query.filter_by(id=user_id).first()
if user:
db.session.delete(user)
db.session.commit()
return {'message': 'User deleted successfully'}
else:
return {'message': 'User not found'}
if __name__ == '__main__':
app.run()
```
注意,在实际开发中需要对数据库连接进行安全处理,比如使用配置文件来存储敏感信息,以避免密码泄露等安全问题。
阅读全文