0
0
FlaskHow-ToBeginner · 3 min read

How to Insert Data Using Flask-SQLAlchemy: Simple Guide

To insert data using flask-sqlalchemy, create an instance of your model class with the data, add it to the session using db.session.add(), and then save it with db.session.commit(). This process stores the new record in the database.
📐

Syntax

Here is the basic syntax to insert data using Flask-SQLAlchemy:

  • model_instance = Model(field1=value1, field2=value2): Create a new record object.
  • db.session.add(model_instance): Add the object to the current database session.
  • db.session.commit(): Commit the session to save changes permanently.
python
new_user = User(name='Alice', email='alice@example.com')
db.session.add(new_user)
db.session.commit()
💻

Example

This example shows a complete Flask app that inserts a new user into the database when run.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

with app.app_context():
    db.create_all()  # Create tables

    new_user = User(name='Alice', email='alice@example.com')
    db.session.add(new_user)
    db.session.commit()

    print(f'Inserted user: {new_user.name} with email {new_user.email}')
Output
Inserted user: Alice with email alice@example.com
⚠️

Common Pitfalls

Common mistakes when inserting data with Flask-SQLAlchemy include:

  • Forgetting to call db.session.commit(), so changes are not saved.
  • Adding the same object multiple times, causing errors.
  • Not creating tables before inserting data, leading to errors.
  • Violating database constraints like unique fields.

Always ensure the session is committed and tables exist before inserting.

python
from flask_sqlalchemy import SQLAlchemy

# Wrong: missing commit
new_user = User(name='Bob', email='bob@example.com')
db.session.add(new_user)
# db.session.commit() missing here

# Right:
db.session.commit()
📊

Quick Reference

Remember these steps to insert data:

  • Create model instance with data.
  • Add instance to session with db.session.add().
  • Save changes with db.session.commit().
  • Ensure tables exist with db.create_all() before inserting.

Key Takeaways

Create a model instance with your data before inserting.
Always add the instance to the session using db.session.add().
Call db.session.commit() to save the data permanently.
Make sure your database tables exist before inserting data.
Avoid forgetting commit or violating database constraints.