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.
String vDateMDYSQL = vDateMDY; java.sql.Date date = new java.sql.Date(0000-00-00); ... prs.setDate(2, date.valueOf(vDateMDYSQL));
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:
ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));
Use java.util.Date:
ps.setDate(2, new java.sql.Date(endDate.getTime()));
Get the current date:
ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));
For tables with TIMESTAMP or DATETIME column types:
Use string:
ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00"));
Use java.util.Date:
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
Get the current timestamp:
ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
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!