New Tutorials:   KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL  
See the Tutorial List

Python MySQL - Drop Table

In this tutorial, we will learn how to delete a MySQL table or drop the table completely from the database using Python.

To completely delete an existing table(both table data and table itself), the DROP TABLE SQL statement is used.

Python MySQL DROP TABLE: Example

Let's assume we have a table with name customers in the studytonight database. Then we can use the below code to drop that table:

import mysql.connector as mysql

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

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)

If the above code will execute without any error it means table named customers is deleted succesfully.

Python MySQL - Drop Table if it exists

The IF EXISTS keyword is used to avoid error which may occur if you try to drop a table which doesn't exist.

When we use the IF EXISTS clause, we are informing the SQL engine that if the given table name exists, then drop it, if it doesn't exists, then do nothing.

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)

If the code executes without an error, then it means the customers table is deleted if it existed.

Here is the snapshot of the actual output:

python mysql drop table output

So in this tutorial we learned how to drop a MySQL table using Python. This is useful when we have some application which creates some temporary tables to store some data and then after the processing, deletes those tables.