Home > Java > javaTutorial > How to Correctly Use `setDate()` and `setTimestamp()` in Prepared Statements?

How to Correctly Use `setDate()` and `setTimestamp()` in Prepared Statements?

DDD
Release: 2024-12-04 11:23:11
Original
983 people have browsed it

How to Correctly Use `setDate()` and `setTimestamp()` in Prepared Statements?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template