Java 17 Recipes


-12. Obtaining Dates for Database Use


Download 3.2 Mb.
Pdf ko'rish
bet239/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   235   236   237   238   239   240   241   242   ...   245
Bog'liq
Java 17 Recipes

12-12. Obtaining Dates for Database Use
 Problem
You want to convert a LocalDate object properly to insert it into a database record.
 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 inserted into a 
database column of type Date.
public class DatesTimes {
static CreateConnection createConn = new CreateConnection();
public static void main(String[] args) {
insertRecord(
"Java 17 Recipes",
"APRESS");
}
private static void insertRecord(
String title,
String publisher) {
String sql = "INSERT INTO PUBLICATION VALUES("
+ "null, ?,?,?)";
LocalDate pubDate = LocalDate.now();
try (Connection conn = createConn.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);) {
pstmt.setString(1, title);
pstmt.setDate(2, java.sql.Date.valueOf(pubDate));
pstmt.setString(3, publisher);
pstmt.executeUpdate();
System.out.println("Record successfully inserted.");
Chapter 12 Working With Databases


476
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
 How It Works
In Java 8, the new Date-Time API (Chapter 
4
) is the preferred API for working with dates 
and times. Therefore, when working with date values and databases, the JDBC API must 
convert between SQL dates and new Date-Time LocalDate objects. The solution to this 
recipe demonstrates that to obtain an instance of java.sql.Date from a LocalDate 
object, you simply invoke the static java.sql.Date.valueOf() method, passing the 
pertinent LocalDate object.
12-13. Closing Resources Automatically

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   235   236   237   238   239   240   241   242   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling