How to Delete a Row of a MySQL Table In Python


In this article, we show how to delete a row of a MySQL table in Python.

So let's say you have a table of Students. There is an entry where the name is Lisa Matthews. You want to delete this name. You can do so in Python easily.

You can also delete multiple entries.

If you need to know how to install MySQL, see How to Install MySQL in Python 3.

So, the code to delete a row of a MySQL table in Python is shown below.

This code deletes the name, Lisa, from the table, Table_name.

This table has a column named firstname.

The full code to delete the name, Lisa, from the table, Table_name is shown below.

So, this is all the code that is needed to delete the name, Lisa, from the MySQL table in Python.

So, the first thing we have to do is import the MySQLdb.

Once we have MySQLdb imported, then we create a variable named db. We set db equal to the MySQLdb.connect() function. This function will allow us to connect to a database. In side of this MySQLdb.connect() function are 4 parameters. These are, MySQLdb.connect("hostname", "username", "password", "database_name"). This line establishes connection with the database that you want.

We then create a variable named cursor, which we set equal to db.cursor(). This establishes a cursor for the database.

Next, we execute our function to delete the row in the table using the cursor.execute() function. Inside of this function, we place in the line, "DELETE FROM Table_name WHERE firstname='Lisa'". So the whole line of code, is, cursor.execute("DELETE FROM Table_name WHERE firstname='Lisa'"). Table_name is the original name of the table.

If the function executes and the row is deleted, a '1' will be output. This alerts you that the rows has been successfully deleted.

With the WHERE clause, you can specify any column. You can also specify multiple columns, using the logical AND operator. Or you can specify an OR operation with the OR operator.

But whatever you specify will be deleted.

If multiple rows meet the criteria that you specify, then all of those rows will be deleted.

If you specify a condition where none of the rows meet the criterion, then the Python shell will return a '0'.

And this is how you can delete a row of a MySQL table in Python.

Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python

HTML Comment Box is loading comments...