To delete data from a SQL database using Python, you need to establish a connection to the database and execute a delete query. Here’s a sample code to delete data in a SQL database using the pyodbc
package
import pyodbc # Connect to the database connection = pyodbc.connect( "Driver={your_driver};" "Server=your_server;" "Database=your_database;" "UID=your_username;" "PWD=your_password;" ) # Create a cursor cursor = connection.cursor() # Delete query delete_query = """ DELETE FROM your_table WHERE condition_column = ? """ # Delete data condition_value = "value_to_delete" cursor.execute(delete_query, condition_value) # Commit the changes connection.commit() # Close the cursor and the connection cursor.close() connection.close() print("Data deleted successfully!")
In the code above, replace 'your_driver'
, 'your_server'
, 'your_database'
, 'your_username'
, 'your_password'
, 'your_table'
, and 'condition_column'
with the actual values corresponding to your SQL database, table, and condition.
The code establishes a connection to the SQL database using the pyodbc.connect()
method.
A delete query is defined with a placeholder (?
) for the condition value.
The condition value is provided as an argument to the cursor.execute()
method.
After deleting the data, the changes are committed using connection.commit()
.
Finally, the cursor and the connection are closed, and a success message is printed to the console.
Make sure to have the pyodbc
package installed. You can install it using pip:
pip install pyodbc
Remember to handle any exceptions that may occur during the database connection or delete operation for proper error handling.