Python and SQLite - Updating Data
In order to update data in an SQLite database, the SQL ‘Update’ statement needs to be used. The following example updates the record in the ‘person’ table that was added in the example for inserting data.
Updating data follows the same pattern as inserting data. Firstly, a check is made to see if the database file actually exists. If it doesn’t, a message is displayed and execution of the program is halted. If successfully found, a connection to the database is established, then the query parameters are defined as variables, which are bound in to the SQL statement when it is executed and a confirmation message is displayed.
One of the parameters is for an ‘id’, so that only the specified record is updated, in this case, the record with an ‘id’ of five. The other parameters are for updating the ‘lastname’ and ‘title’ fields against the record.
The execution of the SQL statement is wrapped in a ‘try-except-finally’ block to catch any errors that may arise and close the database connection at the end.
import os.path import sqlite3 # Database. database = 'testDB.db' connect = None # Check if database file exists. if not os.path.isfile(database): # Confirm incorrect database location and stop program execution. print("Error locating database.") quit() try: # Connect to database. connect = sqlite3.connect(database) except sqlite3.DatabaseError as e: # Confirm unsuccessful connection and quit. print("Database connection unsuccessful.") quit() # Cursor to execute query. cursor = connect.cursor() # Query parameters. lastname = "Bloggs" title = "Mrs" id = 5 # SQL to update data in the person table. sqlUpdate = \ "UPDATE person \ SET lastname = ?, \ title = ? \ WHERE id = ?" try: # Execute query and commit changes. cursor.execute(sqlUpdate, (lastname, title, id)) connect.commit() # Confirm successful updating of person information. print("Person information updated successfully.") except sqlite3.DatabaseError as e: # Confirm error updating person information and stop program execution. print("Error updating person information.") quit() finally: # Close database connection. connect.close()
The contents of the ‘person’ table now looks as follows.