在Flask中使用SQLAlchemy进行数据库操作的步骤如下:
pip install sqlalchemy
pip install flask-sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50), unique=True)
db.create_all()
user = User(username='test', email='test@example.com')
db.session.add(user)
db.session.commit()
users = User.query.all()
user = User.query.filter_by(username='test').first()
user.email = 'new_email@example.com'
db.session.commit()
user = User.query.filter_by(username='test').first()
db.session.delete(user)
db.session.commit()
以上就是在Flask中使用SQLAlchemy进行数据库操作的基本步骤。通过SQLAlchemy,可以方便地进行数据库的增删改查操作。