JDBC PreparedStatement - Insérer une ligne
Un exemple JDBCPreparedStatement pour insérer une ligne dans la base de données.
RowInsert.java
package com.example.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, "example");
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();
}
}
}
Définition de la table.
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
org.postgresql postgresql 42.2.5
Télécharger le code source
$ git clone https://github.com/example/java-jdbc.git