OCJP

Python Code to Delete Data from MySQL Database Table

As we have learned example to Insert Data using Python Code, Display Data using Python Code, Now We are going for an example to delete the data from MySQL Database Table using Python Code. Here is the same method to Connect with database and open the cursor and execute the Query.

import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
  mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="dbphpdemo"
)
  mycursor = mydb.cursor()
   #Delete record now
  query = "Delete from tblwebsitedetails where intSrNo = 9"
  mycursor.execute(query)
  mydb.commit()
  print ("\nRecord Deleted successfully ")


except mysql.connector.Error as error :
    print("Failed to delete record to database: {}".format(error))

finally:
    #closing database connection.
    if(mydb.is_connected()):
        mydb.close()
        print("MySQL connection is closed")

You have to pip install mysql if not already done. We have used the table which was used in our earlier post.

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?