Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to edit data in databases in Flask

Hassan Azhar

Databases in Flask

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

Editing data in the database

The following example demonstrates how data can be edited in sqlite3.

import sqlite3 as sql
def edit_content(title, content):  
    # Connecting to database
    con = sql.connect('shot_database.db')
    # Getting cursor
    c =  con.cursor() 
    # Editing data
    c.execute("UPDATE Shots SET content = %s WHERE title = %s" %(title, content))
    # Applying changes
    print("An error has occured")

This function considers a simplified database table that contains Edpresso shot titles and content. The edit_content function takes the title of the shot whose content is to be changed and the new value that is to be given to the content field in the database in its arguments.

Then, the sql.connect() function returns an SQL connection object. This object calls its cursor() method to return an SQL cursor object. The execute function called using the cursor contains the actual SQL command to be executed. This function updates the content field of the Edpresso Shot, whose title matches that given in the function’s arguments. This command is implemented on the database when the connection’s commit method is called.




Hassan Azhar
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring