How to create table using JDBC example

In any database systems, the goal is to store information in an orderly fashion. The table gets this done by making the table up of columns and rows.

The columns specify what the data is going to be inside table, and the rows contain the actual data.

So the database tables are composed of rows and columns. Each row represents a record in the database. You can make relationship between two or more tables by causing a given column in the table to derive its value from the value of a column in another table. If the tables do not have columns in common, then there would be no way to relate them to each other. Because you can link tables together you can easily extract data from multiple tables with a single query.

Providing the whole information about the database tables is out of scope of this tutorial. So I will just cover basic requirement to create the table using JDBC.

In this example we are going to create a table named PERSON, which has three columns named as PERSON_ID, NAME and AGE. The complete set of SQL statement is given below for creating table in database.

CREATE TABLE PERSON (
    PERSON_ID INTEGER,
    NAME VARCHAR(100),
    AGE INTEGER
);

Below is complete code in java to create the PERSON table using JDBC.

package com.java.connect.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
 
public class JDBCCreateTableExample {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
 
        try {
            // Register the mysql driver
            Class.forName("com.mysql.jdbc.Driver"); // Or any other driver which database you want to connect.
            // Get the connection object
            connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            // Get the statement object
            statement = connection.createStatement();
            // Prepare the Create table SQL query, in this example we are using the PERSON as table name and it has
            // Three columns as PERSON_ID, NAME and AGE
            String CREATE_SQL = "CREATE TABLE PERSON(PERSON_ID INTEGER, NAME VARCHAR(100), AGE INTEGER)";
            // Run the SQL query and check in database if the table has created.
            statement.executeUpdate(CREATE_SQL);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // Finally we have close all the JDBC resources
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}