Inserting Java Date into a Database
When attempting to insert a record with a java.util.Date field into a database, you may encounter an incorrect syntax error. This issue can be resolved by converting the Date object to a suitable SQL data type, such as java.sql.Date or java.sql.Timestamp.
To insert your java.util.Date object, the following steps are recommended:
java.util.Date myDate = new java.util.Date("01/01/2009"); java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
sb.append("INSERT INTO USERS"); sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) "); sb.append("VALUES (?, ?, ?, ?, ?)"); Connection conn = ...; 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); stmt.executeUpdate();
By using java.sql.PreparedStatement and an SQL-compatible data type for your Date field, you can successfully insert the record into the database without encountering syntax errors. Additionally, using PreparedStatement ensures proper escaping of strings, preventing potential security vulnerabilities.
The above is the detailed content of How to Avoid Syntax Errors When Inserting Java Dates into a Database?. For more information, please follow other related articles on the PHP Chinese website!