JDBC Statement – Create a table

A JDBC Statement example to issue a create table SQL to the database.


CREATE TABLE EMPLOYEE
(
    ID serial,
    NAME varchar(100) NOT NULL,
    SALARY numeric(15, 2) NOT NULL,
    CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP
    PRIMARY KEY (ID)
);
TableCreate.java

package com.mkyong.jdbc.statement.table;

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

public class TableCreate {

    private static final String SQL_CREATE = "CREATE TABLE EMPLOYEE"
            + "("
            + " ID serial,"
            + " NAME varchar(100) NOT NULL,"
            + " SALARY numeric(15, 2) NOT NULL,"
            + " CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,"
            + " PRIMARY KEY (ID)"
            + ")";

    public static void main(String[] args) {

		// auto close 
        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement()) {

            // if DDL failed, it will raise an SQLException
            statement.execute(SQL_CREATE);

        } catch (SQLException e) {
            System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Output


A table 'employee' is created.

P.S Tested with PostgreSQL 11 and Java 8

pom.xml

	<dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency>

Download Source Code

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000
newest oldest most voted
Digvijay
Guest
Digvijay

It gives the following error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘NUMBER(5) NOT NULL, USERNAME VARCHAR(20) NOT NULL, CREATED_BY VARCHAR(20) NOT NU’ at line 1

santosh
Guest
santosh

hello sir simple example web service example code in java soap base please …

java tutorials
Guest
java tutorials

A java tutorials for developers

RAJA
Guest
RAJA

Hi why you have created separate variables for all those Driver,Connection,User and Password fields . is there any kind of problem we have to face if we place them directly at where they belongs ?

M Vuong
Guest
M Vuong

Thank Mkyong so much. It amazing!

vijayakumar
Guest
vijayakumar

tis is d one of the most usefull tutorial in w3 ,,,, it helps me more… i like tis ,,,,,,,,,,

trackback
JDBC Tutorials

[…] JDBC Statement example – Create a table Example to create a table in database. […]