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
$ git clone https://github.com/mkyong/java-jdbc.git
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.
I LOVE YOU MAN <3
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
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());
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
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.
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?
to_date is dbms function