简体   繁体   中英

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

Hello my code is throwing ClassCastException . The StackTrace is showing :

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
    at com.affiliate.DAO.AffiliateDAO.insertAffiliate(AffiliateDAO.java:48)

ie @ ps.setDate(6, (Date) affiliate.getDate()); in DAO

Below is my servlet:

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Affiliate af= new Affiliate();

    af.setFisrtName(request.getParameter("txtFname"));
    af.setLastName(request.getParameter("txtLname"));
    af.setGender(request.getParameter("txtGender"));
    af.setCategory(request.getParameter("txtCategory"));
    String dob=(request.getParameter("txtDob"));
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");  
    Date date;
    try {
        date = (Date)formatter.parse(dob);
        af.setDate(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    af.setAge(Integer.parseInt(request.getParameter("txtAge")));
    af.setAddress(request.getParameter("txtAddr"));
    af.setCountry("India");
    af.setState(request.getParameter("txtState"));
    af.setCity(request.getParameter("txtCity"));
    af.setPinCode(Integer.parseInt(request.getParameter("txtPin")));
    af.setEmailId(request.getParameter("txtEmail"));
    af.setStd(Integer.parseInt(request.getParameter("txtStd")));
    af.setContactNo(Integer.parseInt(request.getParameter("txtPhone")));
    af.setMobileNo(Long.parseLong(request.getParameter("txtMobile"),10));

AffiliateService afs=new AffiliateService();
**afs.createAffiliate(af);**
}

Below is my DAO:

public void insertAffiliate(Affiliate affiliate){
    String sql="INSERT INTO REGISTER " +"(id,FisrtName,LastName,Gender,Category,DateOfBirth,Age,Address,Country,State,City,PinCode,EmailId,Std,ContactNo,MobileNo)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    Connection conn = null;

    try {
        **conn = dataSource.createConnection();**
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, affiliate.getId());
        ps.setString(2, affiliate.getFisrtName());
        ps.setString(3, affiliate.getLastName());
        ps.setString(4,affiliate.getGender());
        ps.setString(5, affiliate.getCategory());
        ***ps.setDate(6, (Date) affiliate.getDate());***
        ps.setInt(7, affiliate.getAge());
        ps.setString(8, affiliate.getAddress());
        ps.setString(9,affiliate.getCountry());
        ps.setString(10,affiliate.getState());
        ps.setString(11, affiliate.getCity());
        ps.setInt(12, affiliate.getPinCode());
        ps.setString(13, affiliate.getEmailId());
        ps.setInt(14,affiliate.getStd());
        ps.setInt(15, affiliate.getContactNo());
        ps.setLong(16, affiliate.getMobileNo());

        ps.executeUpdate();
        ps.close();

    } catch (SQLException e) {
        throw new RuntimeException(e);

    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {}
        }
    }
}

Below is my DTO:

public class Affiliate {

@NotNull
    @Past
    Date date;

public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

Please help me in this regard

As the docs say, the Date parameter in the setDate() of PreparedStatement takes a Date object of the type java.sql.Date . But you seemed to have used java.util.Date object in your Affiliate class.

And that is why you get the ClassCastException: java.util.Date cannot be cast to java.sql.Date .

To fix this, you need to either change the type of Date object in your Affiliate class to java.sql.Date or do this

ps.setDate(6, new java.sql.Date(affiliate.getDate().getTime()));

java.sql.Date is a subclass of java.util.Date , not the other way around.

  • java.sql.Date can be cast to java.util.Date .
  • java.util.Date cannot be cast to java.sql.Date .

However, most APIs which sit onto top of JDBC, such as Spring or Hibernate, accept java.util.Date . So almost universally, unless you really need a java.sql.Date , it is better to import java.util.Date .

If using JDBC directly, then for example java.sql.PreparedStatement methods only accept java.sql.Date , so you will have to construct that yourself.

java.sql.ResultSet methods also return java.sql.Date , but they can be directly used as a java.util.Date without further manipulation.

You can't insert util date into sql date

java.util.Date utilDate = affiliate.getDate();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Now, you can insert sqlDate as

ps.setDate(6, sqlDate);

在Servlet import java.util.Date使用import java.sql.Date而不是import java.util.Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM