Search code examples
javamysqldatejdbcsimpledateformat

java.lang.ClassCastException: class java.sql.Date cannot be cast to java.lang.String


I am able to insert the date the insert the data into the database, but when I tried to fetch the data out and show it in the jDateChooser, it showed up the error as the topic stated. why?

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.*;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
import java.util.Date;

these are the packages I imported in

private void DisplayTable(){
        try {
             Class.forName("com.mysql.jdbc.Driver");
               Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/java_his_db","root","");
               String sql = "select * from reservation";
               PreparedStatement ps = con.prepareStatement(sql);
               ResultSet res = ps.executeQuery();
               jTable_reservation.setModel(DbUtils.resultSetToTableModel(res));
               
        }catch (Exception e) {
                                   JOptionPane.showMessageDialog(null, e);
                               }
    }

this is my private void to show the data into jTable

private void jTable_reservationMouseClicked(java.awt.event.MouseEvent evt) {                                                
    // TODO add your handling code here:
    DefaultTableModel model = (DefaultTableModel)jTable_reservation.getModel();

    int rowInd = jTable_reservation.getSelectedRow();

    roomID.setText(model.getValueAt(rowInd, 0).toString());
    customerID.setText(model.getValueAt(rowInd, 1).toString());

    try {
        Date selectin = new SimpleDateFormat("yyyy-MM-dd").parse((String)model.getValueAt(rowInd, 3));
        jDateChooser_in.setDate(selectin);
    } catch (Exception e) {
                               JOptionPane.showMessageDialog(null, e);
                           }
 
}  

these are the code I used to fetch the data into text fields.

the catch exception then showed the error above whenever I clicked one row from the table.

java.lang.ClassCastException: class java.sql.Date cannot be cast to java.lang.String (java.sql.Date is in module java.sql of loader 'platform'; java.lang.string is in module java.base of loader 'boostrap')

how to solve this problem?


Solution

  • From the error, it is clear that the following call returns an object of type java.sql.Date which can not cast into a String.

    model.getValueAt(rowInd, 3)
    

    Simply, do it as follows:

    java.util.Date selectin = model.getValueAt(rowInd, 3);
    

    If you want to format it into some specific pattern (String), you can use SimpleDateFormat to do so e.g.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strDate = sdf.format(selectin);
    

    Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

    You can use Date#toInstant to switch from the java.util.Date to java.time.Instant which is a type from the modern date-time API.

    Instant instant = selectin.toInstant();
    LocalDate dateSelectin = instant.atZone(ZoneId.systemDefault()).toLocalDate();
    String strDateSelectin = dateSelectin.toString();
    

    Replace ZoneId.systemDefault() with the applicable timezone e.g. ZoneId.of("Europe/London") as per your requirement.

    Learn more about the modern date-time API from Trail: Date Time.