如何在Flask中使用SQLAlchemy進(jìn)行數(shù)據(jù)庫操作

sql
小樊
86
2024-08-16 16:28:39
欄目: 云計(jì)算

在Flask中使用SQLAlchemy進(jìn)行數(shù)據(jù)庫操作的步驟如下:

  1. 安裝SQLAlchemy和Flask-SQLAlchemy:
pip install sqlalchemy
pip install flask-sqlalchemy
  1. 配置數(shù)據(jù)庫連接信息:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
  1. 創(chuàng)建數(shù)據(jù)模型:
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)
  1. 創(chuàng)建數(shù)據(jù)庫表:
db.create_all()
  1. 添加數(shù)據(jù):
user = User(username='test', email='test@example.com')
db.session.add(user)
db.session.commit()
  1. 查詢數(shù)據(jù):
users = User.query.all()
  1. 更新數(shù)據(jù):
user = User.query.filter_by(username='test').first()
user.email = 'new_email@example.com'
db.session.commit()
  1. 刪除數(shù)據(jù):
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ù)庫的增刪改查操作。

0