Home >Database >Mysql Tutorial >How to Correctly Use setDate() in Java PreparedStatements to Avoid `IllegalArgumentException`?
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.
<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>
When executing the SQL statement, the following error occurred:
<code>java.lang.IllegalArgumentException at java.sql.Date.valueOf(Date.java:138)</code>
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:
For tables with DATE column type:
Use string:
<code class="language-java"> ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));</code>
Use java.util.Date:
<code class="language-java"> ps.setDate(2, new java.sql.Date(endDate.getTime()));</code>
Get the current date:
<code class="language-java"> ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));</code>
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>
Use java.util.Date:
<code class="language-java"> ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));</code>
Get the current timestamp:
<code class="language-java"> ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));</code>
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!