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
$ git clone https://github.com/mkyong/java-jdbc.git
will this work in a multithreaded environment ,having simultaneous inserts and if the timestamp column is indexed on the db table .
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.
Thank You:)
How to handle Commits and rollbacks???
im using statements not prepared statement..
thank you, saved me a lot of time!
I was wondering if there was any way to execute the below SQL query
old table and new table have the same schema
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.
Thanks a lot it’s really useful
when i insert data to database have Constraint key other table. i don’t now how to do it. Can you help me, please.
how i can insert data from JTextFlield ? please
If possible, could you edit the example to a more realistic case where the ID value is auto-genateated, not known before the insert?
I’ve been referring to your examples quite often lately. Thanks for sharing this great material!
Thanks very useful article for inserting data into DB
Suppose database has different tables.How can i access multiple tables ?
Multiple sql querys ?
Beautiful example, thanks!
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]