Home >Database >Mysql Tutorial >How to Properly Insert java.util.Date Fields into a Database?
Question:
I am encountering an error when attempting to insert a record with a java.util.Date field into a database. The error states that "The syntax of the string representation of a datetime value is incorrect." How can I resolve this issue?
Solution:
To insert a java.util.Date field into a database, you should first consider using an Object Relational Mapping (ORM) solution such as Hibernate to abstract SQL queries. However, if this is not feasible, you can use the following steps:
Example:
java.util.Date myDate = new java.util.Date("10/10/2009"); java.sql.Date sqlDate = new java.sql.Date(myDate.getTime()); Connection conn = ...; // Obtain the database connection String sql = "INSERT INTO USERS (USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) VALUES (?, ?, ?, ?, ?);"; PreparedStatement stmt = conn.prepareStatement(sql); 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(); // Execute the SQL query
This approach automatically escapes strings and prevents SQL injection vulnerabilities.
The above is the detailed content of How to Properly Insert java.util.Date Fields into a Database?. For more information, please follow other related articles on the PHP Chinese website!