Dilini
Dilini

Reputation: 69

How to Insert time in mysql using java

I'm doing a project to catering item hiring service. They want to save the date and time customer hire their items also save the date and time customer return them. Of course any of those not gona be actual at the movement date or time. So first of all I'm trying to find to save any date and time. Other activities will concern later. So I came up with little table. like given below.

 ID   |  Name     |  Value   |    Date    |    Time
(int) | (Varchar) |( Double) | (DateTime) | (DateTime)

And I used this cord to save data.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) 
{                                         
     String date=new SimpleDateFormat("yyyy-MM-dd").format(dat.getDate()); 
     String time = String.valueOf(dateSpinner.getValue()).split(" ")[3];

     try {                                                                                                                                                
         new JDBC().putData("INSERT INTO work (name, balance, date) VALUES ('"+txtName.getText()+"',"+txtValue.getText()+"', '"+date+"', '"+time+"') ");
         JOptionPane.showMessageDialog(null, "value saved");
     } catch (Exception e) {
         JOptionPane.showMessageDialog(null, this.getClass().getName() +" "+e);
     } 
}  

When I'm entering data I'm having

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3" .

Help me to find the error of this cord and save any time. Actually I can save any date using String Date variable. I saved some demo data before I added time field to table. But I'm having this problem when I'm trying to save time. I am using date Spinner to save time. But I can't format it as HH-mm--ss. If you know another time saving feature please let me know. Please help me.

Upvotes: 0

Views: 1022

Answers (1)

Java Devil
Java Devil

Reputation: 10969

This line:

String time = String.valueOf(dateSpinner.getValue()).split(" ")[3];

Is the same as this, just done on a single line

String[] splitArr = String.valueOf(dateSpinner.getValue()).split(" ");
String time = splitArr[3];

The error you are getting is saying that there is not 4 elements in the split array. Put in the below piece of code to debug what you are getting so you know what is happening in that single line

String[] splitArr = String.valueOf(dateSpinner.getValue()).split(" ");
for(int i = 0; i < splitArr.length; i++)
{
     System.out.println("Element number " + i + " is \"" + splitArr[i] + "\"");
}

Then you can update your insert appropriately. Sorry I cant be of more help but we do not know what datespinner is or what datespinner.getValue() returns so do the above to help debug your code.

Upvotes: 1

Related Questions