How to drop a database using JDBC API?

JDBCJava 8Object Oriented ProgrammingProgramming

A. You can drop/delete a database using the DROP DATABASE query.

Syntax

DROP DATABASE DatabaseName;

To drop a Database using JDBC API you need to:

  • Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.

  • Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.

  • Create Statement: Create a Statement object using the createStatement() method of the Connection interface.

  • Execute the Query: Execute the query using the execute() method of the Statement interface.

Example

The show databases command gives you the list of databases in MySQL. First of all, verify the list of databases in it using this command as:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| base               |
| details            |
| exampledatabase    |
| logging            |
| mydatabase         |
| mydb               |
| mysql              |
| performance_schema |
| students           |
| sys                |
| world              |
+--------------------+
12 rows in set (0.00 sec)

Following JDBC program establishes connection with MySQL and drops the database named mydatabase:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DropDatabaseExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to drop a database
      String query = "DROP database MyDatabase";
      //Executing the query
      stmt.execute(query);
      System.out.println("Database dropped......");
   }
}

Output

Connection established......
Database Dropped......

If you verify the list of databases again you cannot find the name mydatabase in it since we have deleted it.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| base               |
| details            |
| exampledatabase    |
| logging            |
| mydb               |
| mysql              |
| performance_schema |
| students           |
| sys                |
| world              |
+--------------------+
11 rows in set (0.00 sec)
raja
Published on 01-Apr-2019 17:44:16
Advertisements