Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A datetime equivalent in java.sql ? (is there a java.sql.datetime ?)

So far, I have not found a clear answer to this.

I'd like to know what the equivalent is for a SQL type DATETIME and the java type, using a PreparedStatement.

I have found: http://www.java2s.com/Code/Java/Database-SQL-JDBC/StandardSQLDataTypeswithTheirJavaEquivalents.htm

But it states that SQL type "DATETIME" is the same as sql.date, but when looking at the SQL date docs (http://download.oracle.com/javase/7/docs/api/java/sql/Date.html), it says the time is truncated (all zeros).

What I want is to be able to specify a preparedStatement.setDateTime() or some sort.

The only other way I see is using a timestamp, but that would require me to change the column type, while I cannot imagine someone else never had this problem before?

Any hints?

Edit: I am using MYSQL.

like image 842
Stefan Hendriks Avatar asked Jul 21 '11 14:07

Stefan Hendriks


People also ask

Does Java sql date have time?

Its main purpose is to represent SQL DATE, which keeps years, months and days. No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java.

What is the difference between Java sql time and Java sql timestamp in Java?

Time represents SQL TIME and only contains information about hour, minutes, seconds and milliseconds without date component. java. sql. Timestamp represents SQL TIMESTAMP which contains both Date and Time information to the nanoseconds precision.

What is sql date in Java?

sql. Date represents the date value in JDBC. The constructor of this class accepts a long value representing the desired date and creates respective Date object. Date(long date) You can create this object using this constructor.

What is the data type for datetime in Java?

TIME Type. The time data type. The format is yyyy- MM -dd hh:mm:ss, with both the date and time parts maintained. Mapped to java.


1 Answers

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);  
like image 149
Bohemian Avatar answered Sep 26 '22 14:09

Bohemian