Monday, 28 July 2014

JDBC Create Table Demo

Enjoyed this tutorial?

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

▶ Subscribe Now

What is CREATE TABLE in JDBC?

In relational database management systems (RDBMS) like MySQL, the CREATE TABLE statement is a Data Definition Language (DDL) command used to define the schema, column names, data types, and integrity constraints of a new table.

With Java Database Connectivity (JDBC), you can automate table creation programmatically right from your Java application without needing external SQL clients.

Executing DDL Using executeUpdate()

To execute SQL DDL commands like CREATE TABLE, Java provides the executeUpdate() method on the Statement interface:

  • executeUpdate(String sql): Executes the given SQL statement. For DDL operations that return nothing, it returns 0.
  • Safe Execution: Adding CREATE TABLE IF NOT EXISTS prevents runtime errors if the target table already exists in the database.

Step-by-Step Code Walkthrough

Here is a clear, complete example showing how to connect to MySQL and create a new table:

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

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

        String sql = "CREATE TABLE IF NOT EXISTS student ("
                   + "id INT PRIMARY KEY AUTO_INCREMENT, "
                   + "name VARCHAR(50) NOT NULL, "
                   + "age INT, "
                   + "email VARCHAR(100)"
                   + ")";

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

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

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

Key Best Practices

  1. Choose Appropriate Data Types: Match database column types (e.g., INT, VARCHAR) properly to your application domain data models.
  2. Define Primary Keys: Always designate a primary key column to ensure uniqueness and optimize query indexing.
  3. Automatic Resource Cleanup: Use the try-with-resources statement to ensure both Connection and Statement are safely closed.

Recommended Related Tutorials

Continue building your database programming skills with these step-by-step guides:


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

Click the below Image to Enlarge

JDBCCreateTableDemo Project Dir Structure
JDBC Create Table Demo
JDBC Create Table Demo
JDBCCreateTable.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCCreateTable
{
    // 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 )
    {

        JDBCCreateTable jdbcCreateTable = new JDBCCreateTable();
        jdbcCreateTable.createTable();

    }

    private void createTable()
    {
        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 = "CREATE TABLE REGISTRATION " + "(id INT not NULL, "
                    + " first VARCHAR(255), " + " last VARCHAR(255), "
                    + " age INT, " + " PRIMARY KEY ( id ))";

            System.out.println(sql);

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

            int returnValue = preparedStatement.executeUpdate();

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

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

        }
        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
CREATE TABLE REGISTRATION (id INT not NULL,  first VARCHAR(255),  last VARCHAR(255),  age INT,  PRIMARY KEY ( id ))
returnValue : 0
Table REGISTRATION has been created

Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download JDBCCreateTableDemoApp Project Click the below link

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

See also:

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

    Post a Comment

    Tutorials