Delete MySQL Table.

We will use SQL DROP Query to delete table in our database student table.

Drop table query to delete MySQL table.
DROP table student
If the table is not available then Error message we will get, so better to use IF EXISTS query while deleting table
DROP table IF EXISTS student
The above DROP table SQL command, we can use in Python script to delete MySQL table.
Here first we have created one SQLAlchemy connection string. Then executed the DROP sql to delete table.
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:password@localhost/database_name")
With query
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_db")    

my_conn.execute("DROP table IF EXISTS student")
Using MySQL connector
import mysql.connector

my_conn = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="password",
  database="my_database"
)
####### end of connection ####
my_cursor = my_conn.cursor()
my_cursor.execute("DROP table IF EXISTS student")
We can capture the error message if any returned by MySQL database by using try except. Here is the code.
import mysql.connector

my_conn = mysql.connector.connect(
  host="localhost",
  user="userid",
  passwd="password",
  database="my_database"
)
####### end of connection ####
my_cursor = my_conn.cursor()
try:
    my_cursor.execute("DROP table  student")
except mysql.connector.Error as my_error:
    print(my_error)
else:
    print("Table deleted ")
Output is here
Table deleted
In above code we have not used IF EXISTS in our SQL statement to generate the error message. Note that if there is no error then the else part will display the message saying Table delete.

Deleting multiple tables

We can change the query to delete multiple tables. Here is the query part.
DROP TABLE `content`, `content_admin`, `content_cat`, `content_cmt_post`

Dropping a unique constraints

We can use DROP sql command to remove unique constraints associated to any column, here is an example.
ALTER TABLE 'content_cat' DROP INDEX  'cat_id'
The above command will remove the unique index associated with cat_id field of content_cat table

Delete MySQL Database

We can also use DROP Sql command to delete a complete database. Here is the sample code
DROP DATABASE TEST
MySQL Delete records More on Error handling
Subscribe to our YouTube Channel here

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer