Drop table using Java JDBC Template

We can drop a table by executing Java JDBC Statement or Prepared Statement, note that the table should not have foreign key references.

table: student
Table Student with records
Java JDBC Code to Drop Table Student:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcExampleTruncateTable {

    public static void main(String[] args) throws SQLException {

        String url = "jdbc:mysql://localhost:3306/my_uat";
        String userName = "root";
        String password = "root123";

        //Drop Student table Query
        String truncateTableQuery = "drop table student";

        Connection connection = null;
        try {

            connection = DriverManager.getConnection(url, userName, password);
            Statement statement = connection.createStatement();

            System.out.println("Student table dropped!...");

        } catch (SQLException e) {
            System.out.println("Exception Occurred while dropping the table Student!");
        } finally {
Output: Student table dropped!...

As I query the database there is not student table now!

mysql> select * from student;
ERROR 1146 (42S02): Table 'my_uat.student' doesn't exist

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap