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

How to Correctly Use setDate() in Java PreparedStatements to Avoid `IllegalArgumentException`?

DDD
Release: 2025-01-18 22:27:11
Original
413 people have browsed it

How to Correctly Use setDate() in Java PreparedStatements to Avoid `IllegalArgumentException`?

Use setDate() method in PreparedStatement

To improve code standardization, you need to replace hardcoded SQL variables with prepared statements and bind them. However, you have a problem using the setDate() method.

Original code

<code class="language-java">String vDateMDYSQL = vDateMDY;
java.sql.Date date = new java.sql.Date(0000-00-00);
...
prs.setDate(2, date.valueOf(vDateMDYSQL));</code>
Copy after login

Error encountered

When executing the SQL statement, the following error occurred:

<code>java.lang.IllegalArgumentException
at java.sql.Date.valueOf(Date.java:138)</code>
Copy after login

Alternatives

The problem is that the date variable is incorrectly initialized using 0000-00-00 as the default value. To resolve this issue, consider the following alternatives when dealing with dates:

java.sql.Date

For tables with DATE column type:

  • Use string:

    <code class="language-java">  ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));</code>
    Copy after login
  • Use java.util.Date:

    <code class="language-java">  ps.setDate(2, new java.sql.Date(endDate.getTime()));</code>
    Copy after login
  • Get the current date:

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

java.sql.Timestamp

For tables with TIMESTAMP or DATETIME column types:

  • Use string:

    <code class="language-java">  ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00"));</code>
    Copy after login
  • Use java.util.Date:

    <code class="language-java">  ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));</code>
    Copy after login
  • Get the current timestamp:

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

Use any of the above methods to correctly set the date in the prepared statement, thus avoiding the error you encountered.

The above is the detailed content of How to Correctly Use setDate() in Java PreparedStatements to Avoid `IllegalArgumentException`?. 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