0

How can I store a specific date from java to my database? (Not only the date today, but also some dates that the user wants to specifiy)

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");       
        Date date = dateFormat.parse(tf.getText());
        String d = dateFormat.format(date); 

        String str = "insert into tableName(tDate) values (?)";
                con = mysqlConnection.dbConnector();
                prs = con.prepareStatement(str);
                prs.setDate(1, // dont know what to put here);

                int rsUpdate = prs.executeUpdate();
                con.close();
                prs.close();
    } catch(ParseException exx) {
                System.err.println(exx);
5
  • Use a second table, which is keyed via a foreign key, to the first Commented Feb 3, 2015 at 6:13
  • Have a look at this SO Post Commented Feb 3, 2015 at 6:17
  • @MadProgrammer Save the 'date' as String first on the other table? Commented Feb 3, 2015 at 6:22
  • Save the date as java.sql.Date...(I also assume you mean you want to store a variable list of dates) Commented Feb 3, 2015 at 6:24
  • possible duplicate of Java Date - Insert into database Commented Feb 4, 2015 at 20:55

2 Answers 2

1

Use

prs.setDate( 1, new java.sql.Date( date.getTime() ) );

The types java.sql.Date and java.sql.Timestamp are suppoed to be used to set date and timestamp fields, respectively. Read their documentation for the differences between them and between them and java.util.Date.

You usually get a java date (java.util.Date) from the user. You convert it to milliseconds since the epoch using getTime(), and then convert back to a java.sql.Date or java.sql.Timestamp as I have shown.

Sign up to request clarification or add additional context in comments.

2 Comments

It inserts a whole bunch of 000's
@meantro Then you should put in your original question: (a) the definition of the table, and (b) the result of System.out.println(date) just before you do the setDate() so that we know it contains valid data.
0

use this it can help

  static  java.sql.Timestamp getSqlDate(Date date) {    
        java.util.Date javaDate = date;
        long javaTime = javaDate.getTime();
        java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime);
        return sqlTimestamp;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.