Home >>Python Tutorial >Pyhton Mysql Delete

Pyhton Mysql Delete

To Delete Records in Python Sql

This is the Python sql delete module of our entire Python MySQL Tutorial. And while using this programming language, if you ever wish to delete the records that you created earlier then that is quite possible. And to accomplish that task you will be required to use the “DELETE FROM” statement. If you wish to delete a particular record with the address of ‘Mountain 21’ then the python mysql delete example for this is mentioned below.  
import mysql.connector

 

mydb = mysql.connector.connect (

host=“localhost” ,

user=“yourusername” ,

passwd=“yourpassword” ,

database=“mydatabase” ,

)



mycursor = mydb.cursor ( )



sql = “DELETE FROM customers WHERE address = ‘Mountain 21’ ”



mycursor.execute ( sql )



mydb.commit ( )



print ( mycursor.rowcount, “record ( s ) deleted” )
  It is important for you to focus on the statement of mydb.commint ( ). This is because of the fact that only because of this statement you will be allowed to make changes to the particular table. Without this statement you will not be allowed to make any changes in the table. It is also important for you to always remember to use the WHERE clause in the DELETE syntax. This is because of the fact that if you forget to use this clause then all the records that you possess will be deleted. Hence, you should always remember to use the WHERE clause while using the DELETE syntax.  

To Prevent SQL Injection

As we have mentioned before in this Python MySQL Tutorial, that it is always a good idea to escape the values of any particular query that you might come across. This statement also stands true in the case of the delete statement. This particular step is done to prevent the SQL injection. This is because of the fact that the SQL injection is a common web hacking technique. This technique is used by hackers from all across the world to misuse or delete your database. It is also important for you to know that the placeholder %s is used in the mysql.connector module to escape the query values in the delete statement. The python mysql delete example for this is mentioned below.  
import mysql.connector



mydb = mysql.connector.connect (

host=“localhost” ,

user=“yourusername” ,

passwd=“yourpassword” ,

database=“mydatabase” ,

)



mycursor = mydb.cursor ( )



sql = “DELETE FROM customers WHERE address = %s ”

adr = ( “Yellow Garden 2”, )



mycursor.execute ( sql, adr )



mydb.commit ( )



print ( mycursor.rowcount, “record ( s ) deleted” )
  With this, we finish the Python sql delete part of our Python MySQL Study Guide.

No Sidebar ads