Python MySQL DROP TABLE

Description

The Python MySQL DROP TABLE command is used to delete a table in a database. Calling this command will not only delete the Table, but irreversibly delete all the data in it too. Hence, you use with caution.

Syntax

DROP TABLE tablename

Example

Remember to import the mysql.connector and create a connection to your database as shown below before attempting anything. Follow up by creating a cursor object which we’ll be using to manipulate to the database.

We will be dropping the Table student using the following code.

import mysql.connector

db = mysql.connector.connect(
  host = "localhost",
  user = "root",
  password = "*********",
  database = "mydatabase"
)

cursor = db.cursor()
cursor.execute("DROP TABLE student")

db.close()

IF EXISTS statement

Adding the IF EXISTS statement to your DROP TABLE provides a check to see if the Table actually exists before deleting it. This is particularly useful as it stops your program from throwing an error and crashing if the Table was not found.

import mysql.connector

db = mysql.connector.connect(
  host = "localhost",
  user = "root",
  password = "*********",
  database = "mydatabase"
)

cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS student")

db.close()

This marks the end of our Python MySQL DROP TABLE Article. Let us know if you have any suggestions or corrections in this Article to make. Contributions to help grow CodersLegacy are more than welcome.

Use this link to head back to main Python MySQL page: link