Home >Database >Mysql Tutorial >How to Properly Use setDate() in PreparedStatements to Avoid IllegalArgumentException?

How to Properly Use setDate() in PreparedStatements to Avoid IllegalArgumentException?

Linda Hamilton
Linda HamiltonOriginal
2025-01-18 22:37:10214browse

How to Properly Use setDate() in PreparedStatements to Avoid IllegalArgumentException?

Avoiding IllegalArgumentException with setDate() in Prepared Statements

Migrating from hardcoded SQL queries to parameterized prepared statements improves code maintainability and security. However, using setDate() can sometimes lead to IllegalArgumentException. This guide demonstrates solutions using java.sql.Date and java.sql.Timestamp.

Handling DATE Columns

For database columns of type DATE, use these methods to correctly set the date parameter:

  • Using a String: Provide a date string in 'yyyy-MM-dd' format:

    <code class="language-java"> ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));</code>
  • Using a java.util.Date: Convert a java.util.Date object:

    <code class="language-java"> java.util.Date endDate = ...; // Your java.util.Date object
     ps.setDate(2, new java.sql.Date(endDate.getTime()));</code>
  • Setting the Current Date: Insert the current date:

    <code class="language-java"> ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));</code>

Handling TIMESTAMP or DATETIME Columns

If your database column is of type TIMESTAMP or DATETIME, use setTimestamp() with these options:

  • Using a String: Provide a date and time string in 'yyyy-MM-dd HH:mm:ss[.f...]' format:

    <code class="language-java"> ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00"));</code>
  • Using a java.util.Date: Convert a java.util.Date object:

    <code class="language-java"> java.util.Date endDate = ...; // Your java.util.Date object
     ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));</code>
  • Setting the Current Timestamp: Insert the current timestamp:

    <code class="language-java"> ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));</code>

By following these guidelines, you can reliably set date and timestamp parameters in your prepared statements, avoiding the IllegalArgumentException. Remember to choose the appropriate method (setDate() or setTimestamp()) based on your database column's data type.

The above is the detailed content of How to Properly Use setDate() in PreparedStatements to Avoid IllegalArgumentException?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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