A datetime equivalent in java.sql ? (is there a java.sql.datetime ?)
Solution 1:
The java.sql package has three date/time types:
-
java.sql.Date
- A date only (no time part) -
java.sql.Time
- A time only (no date part) -
java.sql.Timestamp
- Both date and time
You want the last one: java.sql.Timestamp
.
If you are using these types, you don't need to call a specific setter; just use:
java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());
// The JDBC driver knows what to do with a java.sql type:
preparedStatement.setObject(param);
Solution 2:
The equivalent of MS SQL Server or MySQL DATETIME data type or Oracle DATE data type is java.sql.Timestamp.
Solution 3:
In Java we have java.util.Date to handle both Date and Time values.
In SQL, you have commonly Dates (only dates), Time (only time) and DateTime/Timestamp (date and time).
In your Java program, usually you'll always have java.util.Date, so each time you're setting Dates/Times/DateTimes in PreparedStatements, always choose exactly which one you need, according to the database.