Home >Database >Mysql Tutorial >How to Properly Insert a `java.util.Date` into a Database Using Java?

How to Properly Insert a `java.util.Date` into a Database Using Java?

Susan Sarandon
Susan SarandonOriginal
2025-01-06 10:46:41228browse

How to Properly Insert a `java.util.Date` into a Database Using Java?

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:

  • Escapes strings automatically, preventing potential SQL injection attacks.
  • Provides type safety, ensuring that the correct value is inserted into the database.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn