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

17 comments on “JDBC PreparedStatement – Insert a row

  1. 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.

    Reply
  2. 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.

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

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

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

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

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

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

    Reply
  9. 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

    Reply
  10. 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]

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *