Menu Close

Python MySQL Delete

In this Python MySQL Delete tutorial, we are going to learn all about how to delete records from the database table using the Python MySQL connector.
In previous tutorial, we have seen a complete process to sort the result set.

Make sure you have already installed MySQL connector in your machine using pip as well as create database and table.

Python MySQL Delete

Python MySQL DELETE statement is used to delete the specific record or all the records from the database table.

Example:

In this example we will delete student record whose id is 10.

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database = "demodb",
    port = 3308
	
)
cursor = mydb.cursor()
cursor.execute('DELETE FROM students WHERE id = 10')
mydb.commit()
print(cursor.rowcount, "row deleted.")

Output will be:- I row deleted.

Note:- As you can see in above example, mydb.commit() is required to make changes in database.

Delete All Records:

To delete all the records from the database, you have to omit the where clause.

Example:

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database = "demodb",
    port = 3308
	
)
cursor = mydb.cursor()
cursor.execute('DELETE FROM students')
mydb.commit()
print(cursor.rowcount, "row deleted.")

Note:- You have to always careful about WHERE CLAUSE because if omit to use the where clause in the delete statement it will delete all the records from the database table.

Conclusion

In this Python MySQL Delete, you have learned all about how to delete specific records or all the records from the database table by using the MySQL DELETE statement.
Python MySQL connector is the best for connecting Python applications to the MySQL database and executes SQL queries. After created of database successfully, you can perform a query on that particular database.

If this article for you, please share and keep visiting for further Python MySQL database tutorials.

More Tutorials


More Information:- Click Here

Python MySQL Where Clause
Python MySQL UPDATE Statement

Related Posts