Python SQLite – Deleting Data in Table
To delete data from a table in SQLite using Python, you can use the `DELETE` statement in conjunction with the `execute()` method of the cursor object. 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 `DELETE` statement to delete the desired data from the table.
4. Commit Changes: After executing the `DELETE` 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 delete data from a table named `employees` based on a condition:
“`python
import sqlite3
# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL statement to delete data
cursor.execute(”’
DELETE FROM employees
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 `DELETE` statement that deletes all rows from the `employees` table where the department is `’HR’`.
– We commit the changes to the database using the `commit()` method of the connection object.
– Finally, we close the cursor and connection.