2

I'm using a database in my Java project and I want to store date in it, the 5th and the 6th parameter are Date Object. I used the solution below but I have errors in the indicated lines:

PreparedStatement creerFilm = connecteur.getConnexion().prepareStatement(
        "INSERT INTO FILM (ID, REF, NOM, DISTRIBUTEUR, DATEDEBUT, DATEFIN) "+
        "VALUES (?, ?, ?, ?, ?, ?)");
creerFilm.setInt(1, getId());
creerFilm.setString(2, getReference());
creerFilm.setString(3, getNomFilm());
creerFilm.setString(4, getDistributeur());
// These next two lines
creerFilm.setDate(5, new Date (getDateDebut().getDate()));
creerFilm.setDate(6, new Date (getDateFin().getDate()));
// The above two lines
creerFilm.executeUpdate();
creerFilm.close();

Can you help me to fix that please ?

Thank you

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
bnabilos
  • 2,234
  • 4
  • 23
  • 30

2 Answers2

6

I can't really tell from your code, but you have to use java.sql.Date, not java.util.Date.

Here's how you convert from a utility date instance to an SQL date instance:

java.sql.Date date = new java.sql.Date(utilDate.getTime());
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • 1
    Thank you for your answer. I used the solution you told me and I have no errors now. However I don't know which date format I should use to store it correctly in the database. Currently I'm using a String in the constructor taht should have this format "dd-MM-yyyy", after that I use a function to convert it to SimpleDateFormat. When I use toString() everything works well but when I store it in the database I get something like that in the field "1287525600000" Can you tell me please where is the problem exactly? – bnabilos May 29 '10 at 12:21
  • java.sql.Date has no String constructor. The java.util.Date String constructor is depreciated. java.text.DateFormat has a parse method that works with String dates in the format Jan 12, 1952 or January 12, 1952. If you have a java.text.SimpleDateFormat, you have to parse it to get a java.util.Date. Then you can use the conversion in my answer to get a java.sql.Date. – Gilbert Le Blanc May 29 '10 at 20:42
1

I think detailed answer you can read here: How to insert date in sqlite through java

In a short, you can insert Date as setString (or setInt, or setLong (see the above link), but not setDate):

PreparedStatement ps = connection.prepareStatement(<your sql>);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ps.setString(1, df.format(<your date>));
Community
  • 1
  • 1
kolobok
  • 3,835
  • 3
  • 38
  • 54