How to edit data in databases in Flask
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 sqldef edit_content(title, content):try:# Connecting to databasecon = sql.connect('shot_database.db')# Getting cursorc = con.cursor()# Editing datac.execute("UPDATE Shots SET content = %s WHERE title = %s" %(title, content))# Applying changescon.commit()except: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.
Free Resources