Main Tutorials

JDBC Statement – Insert a row

A JDBC Statement example to insert a row into the database.

RowInsert.java

package com.mkyong.jdbc.statement.row;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;

public class RowInsert {

    public static void main(String[] args) {

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

            int row = statement.executeUpdate(generateInsert("mkyong", new BigDecimal(999.80)));

            // rows affected
            System.out.println(row);

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

    }

    private static String generateInsert(String name, BigDecimal salary) {

        return "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) " +
                "VALUES ('" + name + "','" + salary + "','" + LocalDateTime.now() + "')";

    }

}

Table definition.


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

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
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Chaman Bharti
6 years ago

private static String getCurrentTimeStamp() {

java.util.Date today = new java.util.Date();
return dateFormat.format(today.getTime());

}
Above method is wrong I am facing a problem because of this method. please help me.

LudoviKush
4 years ago

I LOVE YOU MAN <3

geoak
9 years ago

How do you know that the insertion was not failed? Can we detect that or do we need to get the insert id to identify a possible failure

Mirak
8 years ago
Reply to  geoak

This is why try catch block is used for, to catch the SQL Exception error and print a message in case the insertion was failed : System.out.println(e.getMessage());

Anurag
10 years ago

Is it possible to get the primaryID of the newly created row as a return type of insert statement? I want to create a new row in a table, then store the PrimaryId (automatically generated by DB) of that row as a foreign key into another table

abhinav
11 years ago

when i use it i am getting java.lang.nullpointer exception. and i cannot figure out why.
my insert statement is correct and connection also seeems fine. in fact when i run the same code in notepad++ it runs without giving the exception but in eclipse it is showing this exception with every insert statement. please help.

Sajid
12 years ago

Here use to_date() function, where is the definition of this function?
This is not the function of java.util.Date or java.sql.Date classes?

kyu
11 years ago
Reply to  Sajid

to_date is dbms function