Home > Article > Backend Development > How to use Flask-SQLAlchemy for database operations
How to use Flask-SQLAlchemy for database operations
Flask-SQLAlchemy is a convenient extension that can operate databases in Flask applications. It provides simple API to reduce developer workload and integrates seamlessly with the Flask framework. This article will introduce how to use Flask-SQLAlchemy for database operations and provide code examples.
pip install flask-sqlalchemy
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db' db = SQLAlchemy(app)
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = 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.username
if __name__ == '__main__': db.create_all() app.run()
user = User(username='John', email='john@example.com') db.session.add(user) db.session.commit()
all_users = User.query.all() user = User.query.filter_by(username='John').first()
user = User.query.filter_by(username='John').first() user.email = 'newemail@example.com' db.session.commit()
user = User.query.filter_by(username='John').first() db.session.delete(user) db.session.commit()
This is just the basic usage of Flask-SQLAlchemy. It also provides more advanced features such as query filtering, sorting, and paging. You can check out the official documentation of Flask-SQLAlchemy to learn more.
Summary
This article introduces how to use Flask-SQLAlchemy for database operations and provides code examples. With Flask-SQLAlchemy, database operations can be easily handled to speed up development and increase efficiency. Hope this article helps you!
The above is the detailed content of How to use Flask-SQLAlchemy for database operations. For more information, please follow other related articles on the PHP Chinese website!