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 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
6 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
LudoviKushChaman BhartiMirakgeoakAnurag Recent comment authors
newest oldest most voted
Chaman Bharti
Guest
Chaman Bharti

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.

Sajid
Guest
Sajid

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
Guest
kyu

to_date is dbms function

abhinav
Guest
abhinav

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.

Anurag
Guest
Anurag

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

geoak
Guest
geoak

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
Guest
Mirak

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

LudoviKush
Guest
LudoviKush

I LOVE YOU MAN <3

Featured Posts