How to drop a table from a database using JDBC API?

JDBCObject Oriented ProgrammingProgramming

A. The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers, constraints and permission specifications for that table.

Syntax

DROP TABLE table_name;

To drop an table from 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 tables command gives you the list of tables in the current database in MySQL. First of all, verify the list of table in the database named mydatabase using this command as:

mysql> show tables;
+----------------------+
| Tables_in_mydatabase |
+----------------------+
| customers            |
+----------------------+
1 row in set (0.02 sec)

Following JDBC program establishes connection with MySQL and deletes the table named customers from the database named mydatabase:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DropTableExample {
   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/ExampleDatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to drop a table
      String query = "Drop table Customers";
      //Executing the query
      stmt.execute(query);
   }
}

Output

Connection established......
Table Dropped......
raja
Published on 01-Apr-2019 14:25:54
Advertisements