Java Date - Inserting into a Database
To insert a record with a java.util.Date field into a database, you'll need to use java.sql.PreparedStatement with a java.sql.Date or java.sql.Timestamp.
Original Code and Issue
The issue with your original code is that you're trying to insert a java.util.Date directly into the database as a string. Instead, you should convert the java.util.Date to a java.sql.Date and use a prepared statement to insert the value:
java.util.Date to java.sql.Date
java.util.Date myDate = new java.util.Date("01/01/2009"); java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
Prepared Statement
sb.append("INSERT INTO USERS"); sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, CRDATE) "); sb.append("VALUES ( "); sb.append("?, ?, ?, ?, ?"); sb.append(")"); Connection conn = ...; // get the connection somehow PreparedStatement stmt = conn.prepareStatement(sb.toString()); stmt.setString(1, userId); stmt.setString(2, myUser.GetFirstname()); stmt.setString(3, myUser.GetLastname()); stmt.setString(4, myUser.GetSex()); stmt.setDate(5, sqlDate);
Advantages
Using a prepared statement provides several advantages:
The above is the detailed content of How to Properly Insert a `java.util.Date` into a Database Using Java?. For more information, please follow other related articles on the PHP Chinese website!