ClassCastException: java.util.Date 不能转换为 java.sql.Date

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21575253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:27:14  来源:igfitidea点击:

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

javasql

提问by user3222718

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

你好我的代码正在抛出ClassCastException。StackTrace 显示:

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

即@ ps.setDate(6, (Date)affiliate.getDate()); 在 DAO

Below is my servlet:

下面是我的 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:

下面是我的 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:

以下是我的 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

请在这方面帮助我

采纳答案by SudoRahul

As the docssay, the Dateparameter in the setDate()of PreparedStatementtakes a Date object of the type java.sql.Date. But you seemed to have used java.util.Dateobject in your Affiliateclass.

正如文档所说,of 中的Date参数采用类型为 Date 的对象。但是您似乎在您的班级中使用了对象。setDate()PreparedStatementjava.sql.Datejava.util.DateAffiliate

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

这就是为什么你得到ClassCastException: java.util.Date cannot be cast to java.sql.Date.

To fix this, you need to either change the type of Dateobject in your Affiliateclass to java.sql.Dateor do this

要解决此问题,您需要将类中的Date对象类型更改Affiliatejava.sql.Date或执行此操作

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

回答by Ghanshyam

Use import java.sql.Dateinstead of import java.util.Datein your servlet.

在您的 servlet 中使用import java.sql.Date而不是import java.util.Date

回答by Lingasamy Sakthivel

You can't insert util date into sql date

您不能将 util 日期插入 sql 日期

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

Now, you can insert sqlDateas

现在,您可以插入sqlDate

ps.setDate(6, sqlDate);

回答by Stewart

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

java.sql.Date是 的子类java.util.Date,而不是相反。

  • java.sql.Datecan be cast to java.util.Date.
  • java.util.Datecannotbe cast to java.sql.Date.
  • java.sql.Date可以投射到java.util.Date.
  • java.util.Date不能强制转换为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.

但是,大多数位于 JDBC 之上的 API,例如 Spring 或 Hibernate,都接受java.util.Date. 所以几乎普遍,除非你真的需要一个java.sql.Date,否则最好导入java.util.Date.

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

如果直接使用 JDBC,那么例如java.sql.PreparedStatement方法只接受java.sql.Date,因此您必须自己构造它。

java.sql.ResultSetmethods also return java.sql.Date, but they can be directly used as a java.util.Datewithout further manipulation.

java.sql.ResultSet方法也 return java.sql.Date,但它们可以直接用作 ,java.util.Date而无需进一步操作。