0

I am using java.sql.Connection and java.sql.Date to access the date here is my code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     if(jTextArea1.getText().equals(""))
    JOptionPane.showMessageDialog(null, "Please Enter the Expence Description. ");

else if(jComboBox4.getSelectedIndex()<1)
    JOptionPane.showMessageDialog(null, "Please Select the Type.");

else if(jDateChooser1.getDate().equals(""))
    JOptionPane.showMessageDialog(null, "Please Enter the Date. ");

else if(jTextField3.getText().equals(""))
    JOptionPane.showMessageDialog(null, "Please Enter the Amount.");

else{
  try{
    con= DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","1234");
    ps=con.prepareStatement("insert into work values(?,?,?,?)");
    ps.setString(1, jTextArea1.getText());
    ps.setString(2, jCom.getDate());boBox4.getSelectedItem().toString());
    ps.setDate(3, (Date) jDateChooser1.getDate());

But it gives error as

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

Can anyone give the solution for aforesaid?

Abubakkar
  • 15,090
  • 6
  • 52
  • 80

2 Answers2

2

ps.setDate(3, (Date) jDateChooser1.getDate());

Instead of casting the date in the above code, convert util Date to sql Date as below :

java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
Rohit Gulati
  • 522
  • 3
  • 15
1
in fact the format is used yyyy-MM-dd, just use a SimpleDateFormat to format the date value to the desired format when retriving a date value......

SimpleDateFormat dateFormat= new SimpleDateFormat("dd/MM/yyyy");
String strDate = dateFormat.format(rs.getDate("column name"));
amit 1984
  • 414
  • 3
  • 9