This page provides a comprehensive guide to using SQLite with Flask, focusing on the basics of database operations such as creating, querying, and updating data.
Installation
Before you begin, make sure you have Flask installed. You can install Flask using pip:
pip install flask
SQLite with Flask
SQLite is a lightweight database that is perfect for small applications and development purposes. It is also easy to set up and manage.
Database Setup
To use SQLite with Flask, you'll need to create a SQLite database. You can do this by creating a new file with a .db
extension. Here is an example of a simple SQLite database file:
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL
);
Flask Model
In Flask, you can use SQLAlchemy to define models that correspond to your database tables. Here is an example of a Flask model for the users
table:
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
Adding Data
To add data to your database, you can use the session
object provided by SQLAlchemy:
new_user = User(username='john_doe', email='john@example.com')
db.session.add(new_user)
db.session.commit()
Querying Data
You can query data from your database using the session.query()
method:
user = User.query.filter_by(username='john_doe').first()
print(user.email)
Updating Data
To update data in your database, you can modify the object and commit the session:
user.email = 'new_email@example.com'
db.session.commit()
Deleting Data
To delete data from your database, you can use the delete()
method:
user = User.query.filter_by(username='john_doe').first()
db.session.delete(user)
db.session.commit()
Further Reading
For more information on Flask and SQLite, please refer to the following resources:
图片示例
SQLite 数据库结构示意图: