How to get JDBC date format?

I looked at the page and did not find a satisfactory answer.

Is it possible to get the default data format from JDBC?

I am writing a program where the user can select various types of databases (for example, Oracle, MSSQL, etc.) and insert data into it. I need JDBC to tell me which date format is the default.

Is there anyone who has met this case before?

Thanks in advance for your answers.

+1
source share
2 answers

You do not need a date format. You should use PreparedStatement and call setDate or setTimestamp to transfer data. It should not be necessary to convert it to string format, since you should not represent values ​​(or any values) in SQL.

+4
source

Usually you do not need a date format. If you do this, then you treat the dates as strings, saving them as String on the Java side and as VARCHAR on the DB side. This is not true. They should be stored on the Java side as java.util.Date and on the DB side as DATETIME or TIMESTAMP or maybe DATE (if you do not need a temporary part).

The usual way to store dates (over time) is to use PreparedStatement#setTimestamp() :

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

And the usual way to get it back is to use ResultSet#getTimestamp() :

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

This not only eliminates the need to worry about database-specific default date string formats, but it also allows finer-grained control over the selection of dates using > , < , BETWEEN , etc. on the SQL side and finer-grained date formatting using SimpleDateFormat on the Java side.

See also:

+3
source

All Articles