Google News
logo
Python Program to Delete records from an existing table
To delete records from an existing table in Python, you can use the `DELETE` statement in your SQL query. Here's an example :
Program :
import mysql.connector

# Establish a connection to the database
db = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)

# Create a cursor object to execute queries
cursor = db.cursor()

# Define the SQL query to delete records
query = "DELETE FROM tablename WHERE condition"

# Execute the query
cursor.execute(query)

# Commit the changes to the database
db.commit()

# Display the number of rows affected by the query
print(cursor.rowcount, "record(s) deleted")

# Close the database connection
db.close()
In the above program, we are using the `DELETE` statement to delete records from the `tablename` table based on a specified `condition`.

After executing the query, we are committing the changes to the database using the `commit()` method. Finally, we are displaying the number of rows affected by the query using the `rowcount` attribute of the cursor object.