Main Tutorials

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

About Author

author image
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.

Comments

Subscribe
Notify of
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Digvijay
6 years ago

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
9 years ago

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

java tutorials
10 years ago

A java tutorials for developers

RAJA
11 years ago

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
11 years ago

Thank Mkyong so much. It amazing!

vijayakumar
11 years ago

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