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

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

17 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Zak
12 years ago

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

amarjeet kumar
8 years ago

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
8 years ago

Thank You:)

blair
11 years ago

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

Cyber
11 years ago

thank you, saved me a lot of time!

Dhaval
13 years ago

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

Stefania
10 years ago

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 in the User table but not also in the JobProfile. I want also userId is added in the JobProfile table. Thank u.

sayed farag sayed mohamed
10 years ago

Thanks a lot it’s really useful

Hiep Tran
12 years ago

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
12 years ago

how i can insert data from JTextFlield ? please

Mike
12 years ago

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
12 years ago

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

IT JOBS
12 years ago

Thanks very useful article for inserting data into DB

sakib
13 years ago

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

Mirak
11 years ago
Reply to  sakib

Multiple sql querys ?

TSMX
13 years ago

Beautiful example, thanks!

subash
13 years ago

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]