Python MySQL - Delete Query

Python MySQL - Delete Query

To execute a DELETE query in MySQL using Python, you need to use the MySQL connector for Python, which is usually mysql-connector-python or PyMySQL. Here's a step-by-step guide to using mysql-connector-python to perform a DELETE operation.

Firstly, ensure you have the MySQL connector installed. If not, you can install it via pip:

pip install mysql-connector-python 

Here's an example of how to perform a DELETE query:

import mysql.connector # Replace the following with your MySQL database connection details config = { 'user': 'username', 'password': 'password', 'host': 'localhost', 'database': 'database_name', 'raise_on_warnings': True } try: # Establish a database connection connection = mysql.connector.connect(**config) # Create a cursor object using the cursor() method cursor = connection.cursor() # Define the DELETE query. Be sure to use parameterized queries to prevent SQL injection. delete_query = "DELETE FROM table_name WHERE condition_column = %s" delete_value = ("value_to_delete",) # Execute the SQL command cursor.execute(delete_query, delete_value) # Commit your changes in the database connection.commit() # Check if the DELETE was successful print(cursor.rowcount, "records deleted.") except mysql.connector.Error as err: # Handle errors in case anything goes wrong. print("Something went wrong: {}".format(err)) finally: if connection.is_connected(): # Close the cursor cursor.close() # Close the connection connection.close() print("MySQL connection is closed") 

Replace table_name with the name of your table and condition_column with the name of the column that you want to match for deletion (e.g., id). The value_to_delete should be the value you want to match in the condition_column for deletion.

Caution: Be careful with the DELETE statement! Without specifying a WHERE clause, all records in the table will be deleted. Always backup your data before performing DELETE operations.

This is a simple template and doesn't include robust error handling or sophisticated transaction management, so for more complex applications, you'd want to add additional functionality.


More Tags

hotspot groovyshell android-adapter transparency msbuild element-ui confluent-platform http-status-code-400 expo amazon-redshift-spectrum

More Programming Guides

Other Guides

More Programming Examples