Svetlana Svetlana - 2 months ago 8
SQL Question

How to insert datetime field in mySql database using PreparedStatement in java?

I red here about similar questions, but I didn

t find solution for my problem, how to insert datetime field in mySql database using PreparedStatement in java? I didn
t find anything related to this question and PreparedStatement.

So, I have this code:

public void sacuvajDezurstva(List<Dezurstvo> listaDezurstava) throws SQLException {
String sqlSacuvajDezurstva = "INSERT INTO dezurstvo (Datum,IspitniRokID, NastavnikID, PredmetID) VALUES (?,?,?,?)";
PreparedStatement ps = konekcija.prepareStatement(sqlSacuvajDezurstva);

for (Dezurstvo dezurstvo : listaDezurstava) {
ps.setDate(1, new Date(dezurstvo.getDatum().getTime()));
ps.setLong(2, dezurstvo.getIspitniRok().getIspitniRokID());
ps.setLong(3, dezurstvo.getNastavnik().getNastavnikId());
ps.setLong(4, dezurstvo.getPredmet().getPredmetID());

ps.executeUpdate();
}


konekcija.commit();
}


This code works, but the first ps parametar here which is Date is problem, because in database only part of this attribute - Date is saved, precisely day, month and year are saved when I use this method. But hour, minutes and seconds are only 00:00:00. So whole date in database looks like this:

2016-06-26 00:00:00

This column in my datatable where I insert Date is datetime type. And when I do debug, I see that this - dezurstvo.getDatum().getTime()) has the normal value of date inserted through the form. So it has, day, month, year, hour, minutes and seconds, but this ps.setDate, acctualy ps, has only the value of day, month and year.

I presume the problem is in SQL query but I don`t know how to do this when I have only ? in VALUES and not some actual date.

Thanks for help!

Answer

You need to format your date. Try the following

Date date = new Date();
SimpleDateFormat format = new           SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
String currentDateTime = format.format(date);

Then use setString in your prepared statement.

Comments