JDBC PreparedStatement – Create a table

A JDBC PreparedStatement example to create a table in 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.preparestatement.table;

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

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) {

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             PreparedStatement preparedStatement = conn.prepareStatement(SQL_CREATE)) {

            preparedStatement.execute();

        } 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 the Author

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.

Comments

avatar
4 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
NezahualcoyotlDLZN.netValentine GolubevTimoteoInsert timestamp value in PreparedStatement Recent comment authors
newest oldest most voted
Nezahualcoyotl
Guest
Nezahualcoyotl

Wow, it helped me so much. I thought that I just needed the “;” at the end of the sentence, as the SQL standard. I just noticed thanks to you that I don’t really need it :D thanks!!

Valentine Golubev
Guest
Valentine Golubev

why use Create table with preparedStatement?

DLZN.net
Guest
DLZN.net

It’s just an example.

Timoteo
Guest
Timoteo

Excelentes tutoriales, me han ayudado bastante.
Saludos desde México.

trackback
Insert timestamp value in PreparedStatement

[…] preparedStatement.setTimestamp(4,getCurrentTimeStamp()); Note Refer to this full JDBC PreparedStatement insert timestamp example. Can't find what you're looking for? Try Google Custom […]