Topics

Drop Table from Database

Welcome to another tutorial on Python MySQL. Here you will learn about Drop Table, and how to delete a MySQL table or drop the totally by using Python from a database.

The DROP TABLE SQL statement is used to completely delete an existing table, which can be table data or a table itself.

 

Python MySQL DROP TABLE: Example

Suppose, there is a table with customers as the name in the (INSERT DATABASE NAME) database. Check the example below to drop that table.

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword",
    database = "mydatabase1"
)

cursor = db.cursor()
## We have created another table in our database named customers  
## and now we are deleting it
sql = "DROP TABLE customers"

cursor.execute(sql)

From the above, if the code executes without an error, then the table named customers is successfully deleted.

 

Python MySQL - Drop Table if it exists

In Python, the IF EXISTS keyword is used to avoid the error that might occur if you attempt to drop a table that doesn't exist.

Now, if we apply the IF EXISTS clause, then, we are informing the SQL engine that if the given table name exists, then drop it, but, if it doesn't exist, then nothing is done.

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword",
    database = "studytonight"
)

cursor = db.cursor()

sql = "DROP TABLE IF EXISTS customers"

cursor.execute(sql)

From the above example, if the code executes without an error, it means the customers' table is deleted if it existed.