Python SQLite – Update Data
To update data in an SQLite table using Python, you can execute an SQL `UPDATE` statement using the cursor’s `execute()` method. Here’s how you can do it:
1. Establish Connection: Begin by establishing a connection to the SQLite database file using the `connect()` function from the `sqlite3` module.
2. Create Cursor: After establishing the connection, create a cursor object using the `cursor()` method.
3. Execute SQL Statement: Use the cursor’s `execute()` method to execute an SQL `UPDATE` statement to modify the desired data in the table.
4. Commit Changes: After executing the `UPDATE` statement, you need to commit the changes to the database using the `commit()` method of the connection object.
5. Close Cursor and Connection: Finally, close the cursor and connection using the `close()` method to release any resources associated with them.
Here’s an example demonstrating how to update data in a table named `employees`:
“`python
import sqlite3
# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL statement to update data
cursor.execute(”’
UPDATE employees
SET salary = 70000
WHERE department = ‘HR’
”’)
# Commit changes
connection.commit()
# Close cursor and connection
cursor.close()
connection.close()
“`
In this example:
– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute an SQL `UPDATE` statement that modifies the `salary` column for employees in the `HR` department to a new value of `70000`.
– We commit the changes to the database using the `commit()` method of the connection object.
– Finally, we close the cursor and connection.