Python Update Data in SQLite Database
In this article, we’re going to learn how to write code in Python to update a data row of SQLite database table.
You can read below posts to learn how to create new SQLite database and insert data to a table:
For example, we have the SQLite database located at D:\ToriCode\db\contacts.db with the contacts table as below data.
Step 1 - Create Connection to existing SQLite database
Firstly, we need to create a connection to the SQLite database.
import sqlite3
from sqlite3 import Error
connection = None
try:
connection = sqlite3.connect('D:\ToriCode\db\contacts.db')
except Error as e:
print(e)
finally:
if connection:
print('Connect to database successfully.')
Step 2 - Execute Update SQL script to update SQLite data row
Below Python code to implement a function to update contacts row.
def update_contact(conn, contact):
sql_update = ''' UPDATE contacts
SET first_name = ?,
last_name = ?
WHERE id = ?
'''
try:
cursor = conn.cursor()
cursor.execute(sql_update, contact)
connection.commit()
except Exception as e:
print(e)
finally:
print('Execute Update SQL successfully.')
Then we write code invoke the update_contact function above to update contacts row where id is 3.
contact = ('Kealan', 'Parker', 3)
update_contact(connection, contact)
connection.close()
Complete Python program code.
import sqlite3
from sqlite3 import Error
connection = None
try:
connection = sqlite3.connect('D:\ToriCode\db\contacts.db')
except Error as e:
print(e)
finally:
if connection:
print('Connect to database successfully.')
def update_contact(conn, contact):
sql_update = ''' UPDATE contacts
SET first_name = ?,
last_name = ?
WHERE id = ?
'''
try:
cursor = conn.cursor()
cursor.execute(sql_update, contact)
connection.commit()
except Exception as e:
print(e)
finally:
print('Execute Update SQL successfully.')
contact = ('Kealan', 'Parker', 3)
update_contact(connection, contact)
connection.close()
Connect to database successfully.
Execute Update SQL successfully.
After executing the Python program above, we will get the contacts data table to be updated as below.