flask_sqlalchemy实现数据库增删改查代码
时间: 2023-11-22 17:05:44 浏览: 144
基于sqlalchemy对mysql实现增删改查操作
5星 · 资源好评率100%
可以提供如下代码实现基本的增删改查功能:
```
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.name
# 创建数据库表
db.create_all()
# 实现增加用户
@app.route('/add_user')
def add_user():
new_user = User(name='John', email='john@example.com')
db.session.add(new_user)
db.session.commit()
return 'New user has been added!'
# 实现查询用户
@app.route('/find_user')
def find_user():
result = User.query.filter_by(name='John').first()
return 'The email address of the user is ' + result.email
# 实现修改用户
@app.route('/update_user')
def update_user():
user = User.query.filter_by(name='John').first()
user.email = 'new_email@example.com'
db.session.commit()
return 'The email address of the user has been updated!'
# 实现删除用户
@app.route('/delete_user')
def delete_user():
user = User.query.filter_by(name='John').first()
db.session.delete(user)
db.session.commit()
return 'The user has been deleted!'
if __name__ == '__main__':
app.run(debug=True)
```
上述代码实现了基本的增删改查功能,使用flask_sqlalchemy框架操作SQLite数据库。其中,创建了User模型类,包含id、name、email三个字段;同时也包含了增加用户、查询用户、修改用户、删除用户四个接口。在实现上述功能之前,需要先安装相应的依赖包,如需使用MySQL需要另行配置数据库连接信息。
阅读全文