Using setDate in PreparedStatement
To adhere to coding standards, your task is to update your code to utilize prepared statements and bind variables rather than hardcoding SQL variables. However, you have encountered an issue with the setDate() method.
To resolve this, the following guidelines should be followed:
Using java.sql.Date
If your table has a DATE column:
-
java.lang.String:
Use the java.sql.Date.valueOf(java.lang.String) method, providing a string in the "yyyy-[m]m-[d]d" format.
-
java.util.Date:
If you have a java.util.Date variable endDate, convert it using ps.setDate(2, new java.sql.Date(endDate.getTime()));.
-
Current:
To insert the current date, utilize ps.setDate(2, new java.sql.Date(System.currentTimeMillis())); or ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now())); (Java 8 and later).
Using java.sql.Timestamp
For TIMESTAMP or DATETIME columns:
-
java.lang.String:
Use the java.sql.Timestamp.valueOf(java.lang.String) method with timestamps in the "yyyy-[m]m-[d]d hh:mm:ss[.f...]" format.
-
java.util.Date:
Convert java.util.Date variables using ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));.
-
Current:
Obtain the current timestamp using ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis())); or ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now())); (Java 8 and later).
The above is the detailed content of How to Correctly Use `setDate()` and `setTimestamp()` in Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!