How to Delete a Specific Row from SQLite Table using Python?

How to Delete a Specific Row from SQLite Table using Python?

To delete a specific row from an SQLite table using Python, you'd typically use the sqlite3 module that comes bundled with the standard Python library. Here's a step-by-step guide on how to achieve this:

  1. Connect to the SQLite Database:

    import sqlite3 # Connect to the SQLite database (or create it if it doesn't exist) conn = sqlite3.connect('my_database.db') cursor = conn.cursor() 
  2. Delete a Specific Row:

    You can use the DELETE FROM SQL statement to remove a specific row. You should be careful to ensure you are deleting the correct row by using a unique identifier (like a primary key).

    Let's say you have a table named my_table with a primary key column id and you want to delete the row where the id is 5:

    id_to_delete = 5 cursor.execute("DELETE FROM my_table WHERE id=?", (id_to_delete,)) 
  3. Commit the Changes:

    It's essential to commit your changes to the database. Until you call commit(), no changes will be saved.

    conn.commit() 
  4. Close the Connection:

    After you're done with your operations, it's a good practice to close the connection.

    conn.close() 

Here's the complete code to delete a specific row:

import sqlite3 # Connect to the SQLite database conn = sqlite3.connect('my_database.db') cursor = conn.cursor() # Delete row with id 5 id_to_delete = 5 cursor.execute("DELETE FROM my_table WHERE id=?", (id_to_delete,)) # Commit changes conn.commit() # Close connection conn.close() 

Remember:

  • Always backup your database before performing delete operations, especially if you're unsure about the consequences.
  • It's a good practice to use parameterized queries (as shown above with the ? placeholder) to avoid SQL injection attacks and issues with special characters in strings.

More Tags

android-7.0-nougat android-2.2-froyo scipy modelbinder checkstyle long-long knockout.js image-loading bootstrap-selectpicker ssrs-2008

More Programming Guides

Other Guides

More Programming Examples