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")
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