In this article, we will learn how to drop a MySQL database using Python programming. Here, we will use ‘mysql.connector’ library to connect MySQL database and we need a MySQL server to perform this operation.
Prerequisites:
- Python programming
- MYSQL server
- mysql-connector-python library
What is Drop Database operation in MySQL?
‘Drop Database’ is a powerful command to delete a database from the MySQL server. The syntax for the ‘Drop Database’ command is given below:
DROP DATABASE database_name
If the database exists in the MySQL server, the above syntax will delete and remove it from the server. If you want to use the ‘Drop Database’ command to delete a database, make sure that you have backed up all the important data from that database to avoid any data loss. In this article, we will use Python programming to perform the ‘Drop Database’ operation.
Step-by-Step Guide to Drop a Database in MySQL Using Python
Follow the below steps to drop a MySQL database using Python programming:
- Install the ‘mysql-connector-python’ library using the below command:
pip install mysql-connector-python
- Create a connection between MySQL server and Python using the ‘mysql.connector’ library.
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) mycursor = mydb.cursor()
In the above code, replace the ‘localhost’, ‘root’, ‘password’, and ‘mydatabase’ with the respective MySQL server hostname, username, password, and database name.
- Execute the ‘DROP DATABASE’ command to delete the database from the MySQL server using Python programming.
mycursor.execute("DROP DATABASE mydatabase")
In the above code, replace ‘mydatabase’ with the respective database name which you want to delete from the MySQL server.
- Print a message after successfully dropping the database using Python programming.
print("Database has been deleted successfully!")
Example:
Let us see an example that shows how to drop a database called ‘testdb’ from the MySQL server using Python programming.
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("DROP DATABASE testdb") print("Database has been deleted successfully!")
Output:
When you execute the above Python program, you will get the following output:
Database has been deleted successfully!
Conclusion:
In this article, we have learned how to drop a MySQL database using Python programming. We have also discussed what the ‘Drop Database’ operation is in MySQL and how we can use it to delete a database from a MySQL server. We hope this article helps you in your Python programming journey.