How to Avoid Getting an Error When Deleting Non-existing Tables in Python


In this example we will show how to avoid getting an error when deleting tables that do not exist using the IF EXISTS keyword in Python MySQL.

Source Code

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

mycursor = mydb.cursor()

sql = "DROP TABLE IF EXISTS us_state"

mycursor.execute(sql)

mydb.close()

# If the above code is executed with no error, the table was deleted successfully.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments