user354299
user354299

Reputation: 2995

how to store java date type to mysql date type?

how to store java date type to mysql date type?

Upvotes: 3

Views: 2019

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338181

java.time

The modern approach uses java.time classes.

The DATE type in MySQL represents a date only, without time of day and without time zone.

So use LocalDate with a driver compliant with JDBC 4.2.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;

myPreparedStatement.setObject( … , today ) ;

Retrieval.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

Upvotes: 0

Jesper
Jesper

Reputation: 206776

Use a PreparedStatement to execute the SQL statement, like this:

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 it like this, you let the JDBC driver convert it to the format that the database expects, so that your program can remain database independent (you don't need to deal with formatting it in the way that MySQL expects it yourself).

When querying the database, also use PreparedStatement and use the getTimestamp() method on the ResultSet to get the date as a java.sql.Timestamp object.

Upvotes: 0

Ryan Fernandes
Ryan Fernandes

Reputation: 8526

See that your Date is a java.sql.Timestamp (especially if you want hours,mins,sec.. to be persisted)
You could convert a java.util.Date to a Timestamp like so: new Timestamp(date.getTime())

Upvotes: 2

Emil Vikström
Emil Vikström

Reputation: 91892

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

Upvotes: 0

Related Questions