Python SQLite – Update Specific Column
To update a specific column in an SQLite table using Python, you can execute an SQL `UPDATE` statement with the desired column and value specified. 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 column’s 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 a specific column (`salary`) 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 specific column
new_salary = 75000
employee_id = 1 # Example employee ID
cursor.execute(”’
UPDATE employees
SET salary = ?
WHERE id = ?
”’, (new_salary, employee_id))
# 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 the employee with a specific `id` to a new value of `75000`.
– We use parameterized queries to avoid SQL injection and improve security.
– We commit the changes to the database using the `commit()` method of the connection object.
– Finally, we close the cursor and connection.