Google News
logo
Python Program to Delete a table if it exist
To delete a table in MySQL using Python only if it exists, you can use the following program :
Program :
import mysql.connector

# Establishing connection to the database
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# Creating a cursor object
mycursor = mydb.cursor()

# SQL statement to drop table if exists
sql = "DROP TABLE IF EXISTS yourtable"

# Executing the SQL command
mycursor.execute(sql)

# Commit the changes to the database
mydb.commit()

# Closing the database connection
mydb.close()

print("Table deleted successfully!")
Note : Replace `yourusername`, `yourpassword`, `yourdatabase`, and `yourtable` with your own values. This program first checks if the table exists, and if it does, it deletes the table.

If it doesn't exist, it just moves on without throwing any errors. This approach can be useful in cases where you want to make sure the table is deleted before creating a new one with the same name.