Java Reference
In-Depth Information
Problem
You want to convert a LocalDate properly, in order to insert it into a database re-
cord.
Solution
Utilize the static java.sql.Date.valueOf(LocalDate) method to convert a
LocalDate object to a java.sql.Date object, which can be utilized by JDBC for
insertion or querying of the database. In the following example, the current date is in-
serted into a database column of type Date .
private static void insertRecord(
String title,
String publisher) {
String sql = "INSERT INTO PUBLICATION VALUES("
+ "NEXT VALUE FOR PUBLICATION_SEQ, ?,?,?,?)";
LocalDate pubDate = LocalDate.now();
try (Connection conn = createConn.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sql);) {
pstmt.setInt(1, 100);
pstmt.setString(2, title);
pstmt.setDate(3, java.sql.Date.valueOf(pubDate) );
pstmt.setString(4, publisher);
pstmt.executeUpdate();
System.out.println("Record successfully
inserted.");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
How It Works
Search WWH ::




Custom Search