Monday, 28 July 2014

JDBC Drop Table Demo

Enjoyed this tutorial?

Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!

▶ Subscribe Now

What is DROP TABLE in JDBC?

In SQL, the DROP TABLE statement is a Data Definition Language (DDL) command used to permanently remove an existing table structure along with all its data, indexes, constraints, and triggers from a database.

Using Java Database Connectivity (JDBC), you can automate database administration tasks and execute DDL operations directly from your Java programs using the Statement interface.

Executing DDL Commands Using executeUpdate()

While executeQuery() is reserved for queries that return rows (like SELECT), DDL commands such as CREATE, ALTER, and DROP are run using executeUpdate() or execute():

  • executeUpdate(String sql): Executes given SQL commands. For DDL operations (like DROP TABLE), it returns 0.
  • Safe Dropping: Use DROP TABLE IF EXISTS table_name to prevent SQL syntax exceptions if the table does not exist.

Step-by-Step Code Walkthrough

Here is a complete, beginner-friendly example of establishing a connection and dropping a table cleanly:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DropTableDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbcdb";
        String username = "root";
        String password = "password";

        String sql = "DROP TABLE IF EXISTS student";

        try (Connection con = DriverManager.getConnection(url, username, password);
             Statement stmt = con.createStatement()) {

            stmt.executeUpdate(sql);
            System.out.println("Table dropped successfully!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Important Best Practices

  1. Irreversible Operation: Dropping a table cannot be rolled back in most databases once committed. Double-check table names before execution.
  2. Foreign Key Constraints: If other tables reference the target table via foreign keys, ensure dependent child tables or constraints are handled first.
  3. Resource Management: Always close Statement and Connection objects using try-with-resources to avoid memory and connection leaks.

Recommended Related Tutorials

Continue expanding your Java and database management skills with these practical guides:


Click here to watch in Youtube :  https://www.youtube.com/watch?v=gVhizOLxKvk

Click the below Image to Enlarge

JDBCDropTableDemo Project Dir Structure
JDBC Drop Table Demo
JDBC Drop Table Demo
JDBCDropTable.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCDropTable
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL      = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME    = "root";
    static final String PASSWORD    = "root";

    public static void main( String[] args )    
    {

        JDBCDropTable jdbcDropTable = new JDBCDropTable();
        jdbcDropTable.dropTable();

    }

    private void dropTable()
    {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try
        {
            /*
             * Register the JDBC driver in DriverManager
             */

            Class.forName(JDBC_DRIVER);

            /*
             * Establish connection to the Database using DriverManager
             */

            connection = DriverManager
                    .getConnection(DB_URL, USERNAME, PASSWORD);

            String sql = "DROP TABLE REGISTRATION";

            /*
             * Execute the query
             */
            preparedStatement = connection.prepareStatement(sql);

            int returnValue = preparedStatement.executeUpdate();

            System.out.println("returnValue : " + returnValue);

            System.out.println("Table 'REGISTRATION' has been dropped");

        }
        catch( SQLException se )
        {
            /*
             * Handle errors for JDBC
             */
            se.printStackTrace();
        }
        catch( ClassNotFoundException e )
        {
            /*
             * Handle errors for Class.forName
             */
            e.printStackTrace();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if( preparedStatement != null )
                {
                    preparedStatement.close();
                }
            }
            catch( SQLException sqlException )
            {
                sqlException.printStackTrace();
            }
            try
            {
                if( connection != null )
                {
                    connection.close();
                }
            }
            catch( SQLException sqlException )
            {
                sqlException.printStackTrace();
            }
        }

    }
}

Output
returnValue : 0
Table 'REGISTRATION' has been dropped

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCDropTableDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCDropTableDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials