在Flask中使用SQLAlchemy進(jìn)行數(shù)據(jù)庫操作的步驟如下:
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進(jìn)行數(shù)據(jù)庫操作的基本步驟。通過SQLAlchemy,可以方便地進(jìn)行數(shù)據(jù)庫的增刪改查操作。