How to save java date type for mysql date type?

how to save java date type for mysql date type?

+3
source share
3 answers

See what yours Dateis java.sql.Timestamp(especially if you want to save hours, minutes, seconds)

You can convert a java.util.Dateto Timestamplike this:new Timestamp(date.getTime())

+2
source

Use some instance of the Calendar class to convert the date to a string and use the string in your SQL query.

0
source

PreparedStatement SQL, :

Date date = ...;

PreparedStatement ps = connection.prepareStatement("INSERT INTO mytable (this, that, datecol) values (?, ?, ?)");

ps.setString(1, "hello");
ps.setString(2, "world");
ps.setTimestamp(3, new java.sql.Timestamp(date.getTime()));

ps.executeUpdate();

When you do this, you let the JDBC driver convert it to the format that the database expects so that your program remains independent of the database (you don't have to deal with formatting it the way MySQL expects it yourself).

When querying a database, also use PreparedStatementand use the getTimestamp()on method ResultSetto get the date as an object java.sql.Timestamp.

0
source

Source: https://habr.com/ru/post/1747813/


All Articles