The Answer by OscarRyz is correct, and should have been the accepted Answer. But now that Answer is out-dated.
In Java 8 and later, we have the new java.time package (inspired by Joda-Time, defined by JSR 310, with tutorial, extended by ThreeTen-Extra project).
Avoid Old Date-Time Classes
The old java.util.Date/.Calendar, SimpleDateFormat, and java.sql.Date classes are a confusing mess. For one thing, j.u.Date has date and time-of-day while j.s.Date is date-only without time-of-day. Oh, except that j.s.Date only pretends to not have a time-of-day. As a subclass of j.u.Date, j.s.Date inherits the time-of-day but automatically adjusts that time-of-day to midnight (
00:00:00.000). Confusing? Yes. A bad hack, frankly.
For this and many more reasons, those old classes should be avoided, used only a last resort. Use java.time where possible, with Joda-Time as a fallback.
In java.time, the
LocalDate class cleanly represents a date-only value without any time-of-day or time zone. That is what we need for this Question’s solution.
To get that LocalDate object, we parse the input string. But rather than use the old
SimpleDateFormat class, java.time provides a new
DateTimeFormatter class in the java.time.format package.
String input = "01/01/2009" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) ;
LocalDate localDate = LocalDate.parse( input, formatter ) ;
JDBC drivers compliant with JDBC 4.2 or later can use java.time types directly via the
PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO USERS ( USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE ) " +
" VALUES (?, ?, ?, ?, ? )");
pstmt.setString( 1, userId );
pstmt.setString( 3, myUser.getLastName() );
pstmt.setString( 2, myUser.getFirstName() ); // please use "getFir…" instead of "GetFir…", per Java conventions.
pstmt.setString( 4, myUser.getSex() );
pstmt.setObject( 5, localDate ) ; // Pass java.time object directly, without any need for java.sql.*.
But until you have such an updated JDBC driver, fallback on using the java.sql.Date class. Fortunately, that old
java.sql.Date class has been gifted by Java 8 with a new convenient conversion static method,
valueOf( LocalDate ).
In the sample code of the sibling Answer by OscarRyz, replace its "sqlDate =" line with this one:
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate ) ;