2

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

2
  • 6
    new java.sql.Date(date.getTime()) Commented Feb 5, 2014 at 10:58
  • 1
    To elaborate on @Marko's suggestion, a java.sql.Date is a java.util.Date - it extends it. The converse it not true; you need to create a java.sql.Date from the java.util.Date. Commented Feb 5, 2014 at 11:00

4 Answers 4

18

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()));
Sign up to request clarification or add additional context in comments.

5 Comments

hey thank u its working but in db its getting stored as yyyy/MM/dd when in SimpleDateFormat ihave converted it into MM/dd/yyyy.So how to get the date in db in the format MM/dd/yyyy
@user3222718 - If you're storing it as a Date then its DB dependent. If you're storing it as a String, then you can format it using SimpleDateFormat in the format you want and then store it.
'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(); }' this is what i did in my servlet which i ve posted in my question.... Please go through and help me i want the db date in the fromat MM/dd/yyyy
@user3222718 - I say you post this as a new question. AFAIK, if you're storing it as a Date directly, then it probably requires DB configuration to store it in the format you want. But the DB format should be irrelevant as whenever you fetch it back from the DB you'll get the Date object which doesn't have a format of its own. You can use a SDF on that and format it to any type you want to.
@user3222718 the date stored in the DB is most likely stored as milliseconds since the epoch, just like a Date in Java is. A String representation is just that, a representation. When you parse the String using your SimpleDateFormat you are parsing it to a Date. In order so view the date in the database, the database also creates a string representation - to make it human readable. Depending on your database this is easily formatted in much the same way as SimpleDateFormat does it.
7

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.

Comments

4

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

1 Comment

Rather than just posting the code, try to provide explanation and reasoning behind it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.