How to add data to databases in Flask

Databases in Flask

Any sort of database can be used with Flask applications. SQLite will be used for this tutorial since Python has built-in support for SQLite with its sqlite3 module.

Adding data to databases using Flask

Since Flask uses SQLite, some basic operations from the sqlite3 module should be sufficient to add data to the database.

import sqlite3 as sql
def add_data(title, content):
try:
# Connecting to database
con = sql.connect('shot_database.db')
# Getting cursor
c = con.cursor()
# Adding data
c.execute("INSERT INTO Shots (title, content) VALUES (%s, %s)" %(title, content))
# Applying changes
con.commit()
except:
print("An error has occured")

This function adds shot data to a highly simplified Shots database table. It takes the title and content as parameters, connects to the database, spawns a cursor, and uses a string format to execute the SQL command to insert data. Finally, the commit() function is called to confirm and apply changes.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved