2

I've looked through page, and didn't find satisfying answer.

Is there a possibility to get a default data format from JDBC?

I'am writing a program, where user can choose different type of databases (like Oracle, MSSQL etc.) and insert data to it. I need JDBC to say me what is the default format of date.

Is there anybody who has met this case before?

Thank you in advance for answers.

Jarosław Drabek
  • 359
  • 2
  • 4
  • 11

2 Answers2

4

You shouldn't need a date format. You should use PreparedStatement and call setDate or setTimestamp to pass the data. There should be no need to convert it into a string format, as you shouldn't be representing the values (or any values) within the SQL.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

You should usually not care about the date format. If you do, then it means that you're treating dates as strings by storing them as String in Java side and as VARCHAR in DB side. This is wrong. They should in Java side be stored as java.util.Date and in DB side as DATETIME or TIMESTAMP or maybe DATE (if you don't care about the time part).

The normal way to store a date (with time) is to use PreparedStatement#setTimestamp():

preparedStatement = connection.prepareStatement("INSERT INTO person (birthdate) VALUES (?)");
preparedStatement.setTimestamp(1, new Timestamp(date.getTime()));
// ...

And the normal way to retrieve it back is to use ResultSet#getTimestamp():

Date date = resultSet.getTimestamp("birthdate");
// ...

This not only removes the need to worry about DB-specific default date string formats, but this also allows for more fine grained control over selecting dates using >, <, BETWEEN, etc in SQL side and more fine grained date formatting using SimpleDateFormat in Java side.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555