How to use Flask-SQLAlchemy for database operations

WBOY
Release: 2023-08-02 08:39:21
Original
1261 people have browsed it

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.

  1. Install Flask-SQLAlchemy
    First, you need to install the Flask-SQLAlchemy extension. It can be installed by running the following command in a command line window using the pip command:
pip install flask-sqlalchemy
Copy after login
  1. Configuring the database connection
    Add the database connection configuration in the Flask application's configuration file. Different databases such as MySQL, SQLite, PostgreSQL etc. can be used. The following is an example configuration using a SQLite database:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db' db = SQLAlchemy(app)
Copy after login
  1. Define the model
    Using Flask-SQLAlchemy, you can define a model to map tables in the database. A model is a Python class that corresponds to a table and the columns of the table in the database. The following is the definition of an example model:
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 '' % self.username
Copy after login
  1. Create database table
    In Flask-SQLAlchemy, you can use the db.create_all() method to create a database table. This method can be called when the application starts to ensure the correctness of the database structure. Here is an example:
if __name__ == '__main__': db.create_all() app.run()
Copy after login
  1. Perform database operations
    With Flask-SQLAlchemy, you can easily perform database operations such as inserting, querying, updating, and deleting data. Here are some basic examples:
  • Insert data:
user = User(username='John', email='john@example.com') db.session.add(user) db.session.commit()
Copy after login
  • Query data:
all_users = User.query.all() user = User.query.filter_by(username='John').first()
Copy after login
  • Update data:
user = User.query.filter_by(username='John').first() user.email = 'newemail@example.com' db.session.commit()
Copy after login
  • Delete data:
user = User.query.filter_by(username='John').first() db.session.delete(user) db.session.commit()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!