python-mysqlHow do I delete a row from a MySQL database using Python?
To delete a row from a MySQL database using Python, you can use the cursor.execute() method of the MySQLConnection object. This method takes two parameters: the query string and a list of parameters to be used in the query.
The query string should be a DELETE statement, followed by the WHERE clause containing the conditions for which rows should be deleted.
Below is an example of deleting a row from a table named students:
import mysql.connector
# Connect to the database
conn = mysql.connector.connect(user='user', password='password',
host='localhost',
database='school')
# Create a cursor object
cursor = conn.cursor()
# Execute the query
cursor.execute("DELETE FROM students WHERE name = %s", ('John',))
# Commit the changes
conn.commit()
Code explanation
import mysql.connector: This imports the MySQL Connector/Python library.conn = mysql.connector.connect(user='user', password='password', host='localhost', database='school'): This creates a connection object to the MySQL database.cursor = conn.cursor(): This creates a cursor object to execute the query.cursor.execute("DELETE FROM students WHERE name = %s", ('John',)): This executes theDELETEstatement with the parameter'John'to delete the row from thestudentstable where thenamecolumn is equal to'John'.conn.commit(): This commits the changes to the database.
Helpful links
More of Python Mysql
- How can I create a web application using Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I access MySQL using Python?
- How can I connect Python and MySQL?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How can I convert data from a MySQL database to XML using Python?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...