JDBC PreparedStatement – Insert a row

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

RowInsert.java

package com.mkyong.jdbc.preparestatement.row;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;

public class RowInsert {

    private static final String SQL_INSERT = "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) VALUES (?,?,?)";

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

            preparedStatement.setString(1, "mkyong");
            preparedStatement.setBigDecimal(2, new BigDecimal(799.88));
            preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));

            int row = preparedStatement.executeUpdate();

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

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

    }

}

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
16 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
17 Comment authors
amarjeet kumarAlfaz JikaniStefaniasayed farag sayed mohamedMirak Recent comment authors
newest oldest most voted
blair
Guest
blair

How to handle Commits and rollbacks???
im using statements not prepared statement..

Zak
Guest
Zak

will this work in a multithreaded environment ,having simultaneous inserts and if the timestamp column is indexed on the db table .

Stefania
Guest
Stefania

Hi! I’ve got a little problem with a query. I have to insert records in the User table. In the database postgres User table joins to JobProfile with the key userId. So when I add a new user, userId is addes in User table and JobProfile. How can I do join in java? I’ve never used it. Can you write the query please? This is my query: String string=”INSERT INTO “User” (“userId”,”name”,”surname”,”mail”,”password”,”status”) Values(?,?,?,?,?,?)”; PreparedStatement ad=db.con.prepareStatement(string); ad.setString(1,user.getUserId()); ad.setString(2,user.getName()); ad.setString(3, user.getSurname()); ad.setString(4, user.getEmail()); ad.setString(5, user.getPassword()); ad.setBoolean(6, user.getStatus()); ad.executeUpdate(); So when I add a new user with this query, the user is added… Read more »

sayed farag sayed mohamed
Guest
sayed farag sayed mohamed

Thanks a lot it’s really useful

Cyber
Guest
Cyber

thank you, saved me a lot of time!

Hiep Tran
Guest
Hiep Tran

when i insert data to database have Constraint key other table. i don’t now how to do it. Can you help me, please.

narvouzi
Guest
narvouzi

how i can insert data from JTextFlield ? please

Mike
Guest
Mike

If possible, could you edit the example to a more realistic case where the ID value is auto-genateated, not known before the insert?

Jake
Guest
Jake

I’ve been referring to your examples quite often lately. Thanks for sharing this great material!

IT JOBS
Guest
IT JOBS

Thanks very useful article for inserting data into DB

sakib
Guest
sakib

Suppose database has different tables.How can i access multiple tables ?

Mirak
Guest
Mirak

Multiple sql querys ?

TSMX
Guest
TSMX

Beautiful example, thanks!

Dhaval
Guest
Dhaval

I was wondering if there was any way to execute the below SQL query

INSERT INTO NEW_table(SELECT * FROM OLD_table where city like 'NEW %');

old table and new table have the same schema

subash
Guest
subash

I’m new to here, i leek u website its very helpful to learn java tutorials
i need a code to upload those details in database
[videoname, title, description, duration of video, image file of video, video or filepath of the video]

amarjeet kumar
Guest
amarjeet kumar

how can use select query inside insert in PreparpreparedStatement.

ex; if I have used select max(id) from table and pass in preaparestmt for increment of id. I know index is a solution for same. But we cane use select in same or not.

Alfaz Jikani
Guest
Alfaz Jikani

Thank You:)