Error - java.util.Date cannot be cast to java.sql.Date when saving data

Asked

Viewed 471 times

0

When trying to write the data to the database, the program points me to this Exception:java.lang.Classcastexception: java.util.Date cannot be cast to java.sql.Date. The first code slime is Servlet and the second code block is my Dao class.

package br.com.caelum.agenda.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.caelum.jdbc.dao.ContatoDao;
import br.com.caelum.jdbc.modelo.Contato;

@WebServlet("/AdicionaContato")

public class AdicionaContatoServlet extends HttpServlet {

    protected void service(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException{
        //busca o writer
        PrintWriter out = response.getWriter();

        //pega os parametros digitados através do request

        String nome = request.getParameter("nome");
        String email = request.getParameter("email");
        String endereco = request.getParameter("endereco");
        String dataEmTexto = request.getParameter("dataNascimento");
        Calendar dataNascimento = null;

        //fazer a conversão da data
        try {
            Date date = (Date) new SimpleDateFormat("dd/MM/yyyy").parse(dataEmTexto);
            dataNascimento = Calendar.getInstance();
            dataNascimento.setTime(date);
        }catch (ParseException e) {
            out.println("Erro ao converter data");
            return; //retorna a execução do método
            }
        //monta um objeto contato

        Contato contato = new Contato();
        contato.setNome(nome);
        contato.setEmail(email);
        contato.setEndereco(endereco);
        contato.setDataNascimento(dataNascimento);

        //salva o contato
        ContatoDao dao = new ContatoDao();
        dao.adiciona(contato);

        //imprime o nome do contato adicionado
        out.println("<html>");
        out.println("<body>");
        out.println("Contato" + contato.getNome() + "adiconado com sucesso!");
        out.println("</body>");
        out.println("</html>");
        }
}        








package br.com.caelum.jdbc.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.caelum.jdbc.modelo.Contato;
import br.com.caelum.jdbc1.ConnectionFactory;

public class ContatoDao {
    private Connection connection;

    public ContatoDao() {
        this.connection = new ConnectionFactory().getConnection();

    }

    public void adiciona(Contato contato) {
        String sql = "insert into contatos" + "(nome,email,endereco,dataNascimento)" + "values (?,?,?,?)";


    try {
        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setString(1,contato.getNome());
        stmt.setString(2,contato.getEmail());
        stmt.setString(3,contato.getEndereco());
        stmt.setDate(4,new java.sql.Date(contato.getDataNascimento().getTimeInMillis()));

        stmt.execute();
        stmt.close();
    }
    catch(SQLException e) {
        throw new RuntimeException(e);

    }
    }
    public List<Contato> getLista(){
        try {
            List<Contato> contatos = new ArrayList<Contato>();
            PreparedStatement stmt = this.connection.prepareCall("select *from contatos");
            ResultSet rs = stmt.executeQuery();

            while(rs.next());

            Contato contato = new Contato();
            contato.setId(rs.getLong("id"));
            contato.setNome(rs.getString("nome"));
            contato.setEndereco(rs.getString("endereco"));
            Calendar data = Calendar.getInstance();
            data.setTime(rs.getDate("dataNascimento"));

            contatos.add(contato);

            rs.close();
            stmt.close();
            return contatos;
        }catch (SQLException e) {
            throw new RuntimeException (e);
        }
}
}

1 answer

0


This error is happening because the parse method of the Simpledateformat class returns a Date from the java.util package and you are trying to cast for a java.sql.Date.

You can resolve this by making explicit which Date to use and will not need to cast.

  java.util.Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dataEmTexto);

or by changing the import in the Add-Contact class to java.util.date, then you can use it this way.

Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dataEmTexto);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.