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 theDELETE
statement with the parameter'John'
to delete the row from thestudents
table where thename
column is equal to'John'
.conn.commit()
: This commits the changes to the database.
Helpful links
More of Python Mysql
- How do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...