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

夙愿已清 提交于 2019-11-30 20:52:44

问题


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


回答1:


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()));



回答2:


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.




回答3:


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);



回答4:


Use import java.sql.Date instead of import java.util.Date in your servlet.



来源:https://stackoverflow.com/questions/21575253/classcastexception-java-util-date-cannot-be-cast-to-java-sql-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!