Delete

4 respostas
A

Estou com um exercício e JSP e tenho que deletar um registro do DB e não estou conseguindo, segue meu código:

public void deletaFuncionario(String nome, String email, String sexo, int cargo) throws SQLException {

	    Connection con          = getConnection();
	    PreparedStatement stmt  = con.prepareStatement("delete tb_func f, tb_cargos c where (c.id_cargo = f.id_cargo) ");
	    stmt.setString(1, nome);
	    stmt.setString(2, sexo);
	    stmt.setInt(3, cargo);
	    stmt.setString(4, email);

	    if (stmt.executeUpdate() <= 0) {
	        throw new SQLException("Could not update funcionario " + nome);
	      }

    con.close();

  }

Na página JSP existe um button Submit para chamar esse método que está funcionando. Alguém pode dá uma help.

4 Respostas

Jair_Rillo_Junior

Vai ter Servlet? ou apenas JSP + JavaBeans?

Dá uma pesquisada nos artigos do GUJ que fala mais sobre Servlet.

loganwlogan

Cara colega, não entendi bem sua dúvida oq exatamente não funciona? reparei que vc não passa a url, user e senha na hora de conectar no banco, não seria esse o seu problema? se não for colque mais informações para podermos ajudá-lo.

[]´s

Logan

B

Sua sintaxe do delete está errada.

Vc deve usar “delete from NOME_TABELA where CONDIÇÕES…”

Abraço.

A
Alguém poderia informar o que está errado, pois não estou conseguindo deletar um registro. Segue meu código. Classe com os comandos SQL e conexão DB.
package br.com.recjug.exemplostruts;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.LinkedList;

import br.com.recjug.exemplostruts.vos.Cargo;
import br.com.recjug.exemplostruts.vos.Funcionario;

/**
 *  Fachada do sistema. (Mais ou menos)
 *
 *@author     freitas
 *@created    31 de Janeiro de 2003
 */
public class FachadaModelo {
  private static FachadaModelo instancia;


  /**
   *  Constructor for the Fachadao object
   */
  private FachadaModelo() { }


  /**
   *  Retorna a instância da fachada
   *
   *@return    The instance value
   */
  public static FachadaModelo getInstance() {
    if (instancia == null) {
      instancia = new FachadaModelo();
    }

    return instancia;
  }


  /**
   *  Testando a classe fachada
   *
   *@param  args  The command line arguments
   */
  public static void main(String[] args) {
    try {
      FachadaModelo f  = new FachadaModelo();
      f.getConnection();
      System.out.println("td blz");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  /**
   *  Gets the cargos attribute of the FachadaModelo object
   *
   *@return                   The cargos value
   *@exception  SQLException  Se o acesso aos dados acusar erro
   */
  public Collection getCargos() throws SQLException {
    LinkedList<Cargo> cargos  = new LinkedList<Cargo>();

    Connection con     = getConnection();
    Statement stmt     = con.createStatement();
    ResultSet rs       = stmt.executeQuery("SELECT * FROM TB_CARGOS ORDER BY NOME");

    while (rs.next()) {
      cargos.add(new Cargo(rs.getInt("ID_CARGO"), rs.getString("NOME")));
    }

    rs.close();
    stmt.close();
    con.close();

    return cargos;
  }


  /**
   *  Gets the funcionarios attribute of the FachadaModelo object
   *
   *@return                   The funcionarios value
   *@exception  SQLException  Se o acesso aos dados acusar erro
   */
  public Collection getFuncionarios() throws SQLException {
    LinkedList<Funcionario> funcs  = new LinkedList<Funcionario>();
    Connection con    = getConnection();
    Statement stmt    = con.createStatement();
    ResultSet rs      = stmt.executeQuery("select f.*, c.nome as nome_cargo " +
        "from tb_func f " +
        "inner join tb_cargos c on (c.id_cargo = f.id_cargo) order by f.nome");

    while (rs.next()) {
      funcs.add(new Funcionario(rs.getString("nome"), rs.getString("email"),
          rs.getString("nome_cargo"), rs.getString("sexo")));
    }

    rs.close();
    stmt.close();
    con.close();

    return funcs;
  }

  /**
   *  Gets the funcionario attribute of the FachadaModelo object with PK
   *
   *@return                   The funcionarios value
   *@exception  SQLException  Se o acesso aos dados acusar erro
   */
  public Funcionario getFuncionario(String email) throws SQLException {
    Funcionario func  = null;
    Connection con    = getConnection();
    Statement stmt    = con.createStatement();
    ResultSet rs      = stmt.executeQuery("select f.*, c.nome as nome_cargo " +
        "from tb_func f " +
        "inner join tb_cargos c on (c.id_cargo = f.id_cargo) where f.email = '"+email+"' ");

    if (rs.next()) {
      func = new Funcionario(rs.getString("nome"), rs.getString("email"),
          rs.getString("id_cargo"), rs.getString("sexo"));
    }

    rs.close();
    stmt.close();
    con.close();

    return func;
  }

  /**
   *  Gets the funcionario attribute of the FachadaModelo object with PK
   *
   *@return                   The funcionarios value
   *@exception  SQLException  Se o acesso aos dados acusar erro
   */
  public void editaFuncionario(String nome, String email, String sexo, int cargo) throws SQLException {

	    Connection con          = getConnection();
	    PreparedStatement stmt  = con.prepareStatement("update tb_func set nome = ? , sexo = ? , id_cargo = ? where email = ? ");
	    stmt.setString(1, nome);
	    stmt.setString(2, sexo);
	    stmt.setInt(3, cargo);
	    stmt.setString(4, email);

	    if (stmt.executeUpdate() <= 0) {
	        throw new SQLException("Could not update funcionario " + nome);
	      }

    con.close();

  }

  
  /**
   *  Gets the funcionario attribute of the FachadaModelo object with PK
   *
   *@return                   The funcionarios value
   *@exception  SQLException  Se o acesso aos dados acusar erro
   */
  public void deletaFuncionario(String nome, String email, String sexo, int cargo) throws SQLException {

	    Connection con          = getConnection();
	    PreparedStatement stmt  = con.prepareStatement("delete from tb_func");
	    stmt.setString(1, nome);
	    stmt.setString(2, sexo);
	    stmt.setInt(3, cargo);
	    stmt.setString(4, email);

	    if (stmt.executeUpdate() <= 0) {
	        throw new SQLException("Could not update funcionario " + nome);
	      }

    con.close();

  }
 
  /**
   *  Gets the funcionario attribute of the FachadaModelo object
   *
   *@param  email  Description of the Parameter
   *@return        The funcionario value
   */
  public boolean existeFuncionario(String email) {
    return false;
  }


  /**
   *  Insere um funcionario na base de dados
   *
   *@param  nome              Nome
   *@param  email             Email
   *@param  cargo             Id do cargo
   *@param  sexo              Sexo
   *@exception  SQLException  Se o acesso aos dados acusar erro
   */
  public void insereFuncionario(String nome, String email, int cargo, String sexo) throws SQLException {
    Connection con          = getConnection();
    PreparedStatement stmt  = con.prepareStatement("insert into tb_func(nome, email, sexo, id_cargo) values(?, ?, ?, ?)");
    stmt.setString(1, nome);
    stmt.setString(2, email);
    stmt.setString(3, sexo);
    stmt.setInt(4, cargo);

    if (stmt.executeUpdate() <= 0) {
      throw new SQLException("Could not insert funcionario " + nome);
    }
  }


  /**
   *  Gets the connection attribute of the FachadaModelo object
   *
   *@return                   Uma conexão à base de dados
   *@exception  SQLException  Description of the Exception
   */
  private Connection getConnection() throws SQLException {
    Connection con  = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost", "sa", "");
    return con;
  }

  static {
    try {
      Class.forName("org.hsqldb.jdbcDriver");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Classe que seleciona o registro para ser deletado.
package br.com.recjug.exemplostruts.actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.recjug.exemplostruts.FachadaModelo;
import br.com.recjug.exemplostruts.vos.Funcionario;

public class PreDeletaAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {

		String email = request.getParameter("email");
		System.out.println("Email: " + email);

		try {
			FachadaModelo fachada  = FachadaModelo.getInstance();

			//Busca o funcionario
			Funcionario func       = fachada.getFuncionario(email);
			request.getSession(true).setAttribute("func", func);

			return mapping.findForward("sucesso");
		} catch (SQLException e) {
			ActionErrors erros  = new ActionErrors();
			erros.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.sqlerror"));
			saveErrors(request, erros);
			return mapping.findForward("excecoes");
		}
	}

}
Classe com o método deletar:
package br.com.recjug.exemplostruts.actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.recjug.exemplostruts.FachadaModelo;
import br.com.recjug.exemplostruts.forms.CadastreForm;

public class DeletaAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
	    try {
	        FachadaModelo fachada  = FachadaModelo.getInstance();
	        CadastreForm cform     = (CadastreForm) form;
	        int idCargo            = Integer.parseInt(cform.getCargo());
	        fachada.deletaFuncionario(cform.getNome(), cform.getEmail(), cform.getSexo(), idCargo);
	        System.out.println("Deletou beleza");
	        return mapping.findForward("sucesso");
	      } catch (SQLException e) {
	        e.printStackTrace();
	        ActionErrors erros  = new ActionErrors();
	        erros.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.sqlerror"));
	        saveErrors(request, erros);
	        return mapping.findForward("excecoes");
	      }

		
		
	}

}
Página delete JSP
<%@ page language="java"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
	prefix="html"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
	prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
	prefix="logic"%>

<html:html locale="true">

<head>
<title><bean:message key="index.title" /></title>
<html:base />
</head>
<body bgcolor="white">
<html:form action="/deleta">
	<h2>Deletar funcionários</h2>
	<table>
      <tr><td>Nome:</td><td><html:text name="func" property="nome"/><html:errors property="nome"/></td></tr>
      <tr><td>email:</td><td><html:text readonly="true" name="func" property="email"/><html:errors property="email"/></td></tr>
      
      <tr><td><html:submit/></td><td></td></tr>
    </table>
</html:form>
<br>
<html:link page="/index.jsp">Retornar ao índice</html:link>
</body>

</html:html>

Meu XML

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

    <form-beans>
	    <form-bean name="cadastreForm" type="br.com.recjug.exemplostruts.forms.CadastreForm"/>
    </form-beans>

<!-- =================================== Global Forward Definitions -->

    <global-forwards>
		<forward name="welcome"  path="/Welcome.do" />
		<forward name="excecoes" path="/jsp/error.jsp" />
    </global-forwards>

<!-- =================================== Action Mapping Definitions -->

    <action-mappings>

        <action
            path="/Welcome"
            type="org.apache.struts.actions.ForwardAction"
            parameter="/pages/Welcome.jsp" />

		<action type="br.com.recjug.exemplostruts.actions.ListarAction"
	            path="/listar">
			<forward name="sucesso" path="/jsp/lista.jsp"/>
		</action>

		<action type="br.com.recjug.exemplostruts.actions.PreencheFormAction"
	            path="/preencheform">
			<forward name="cadastro" path="/jsp/cadastro.jsp"/>
		</action>

		<action type="br.com.recjug.exemplostruts.actions.CadastreAction"
				path="/cadastre"
				name="cadastreForm"
				scope="request"
				validate="true"
				input="/jsp/cadastro.jsp">
			<forward name="sucesso" path="/listar.do"/>
		</action>


		<action type="br.com.recjug.exemplostruts.actions.PreEditaAction"
				path="/preEdita">
			<forward name="sucesso" path="/jsp/edita.jsp"/>
		</action>

		<action type="br.com.recjug.exemplostruts.actions.EditaAction"
				path="/edita"
				name="cadastreForm"
				scope="request"
				validate="true"
				input="/jsp/edita.jsp">
			<forward name="sucesso" path="/listar.do"/>
		</action>
		
		<action type="br.com.recjug.exemplostruts.actions.PreDeletaAction"
				path="/preDeleta">
			<forward name="sucesso" path="/jsp/deleta.jsp"/>
		</action>
		
		<action type="br.com.recjug.exemplostruts.actions.DeletaAction"
				path="/deleta"
				name="cadastreForm"
				scope="request"
				validate="true"
				input="/jsp/deleta.jsp">
			<forward name="sucesso" path="/listar.do"/>
		</action>
		
		
	</action-mappings>
	
	<message-resources parameter="resources.application" /> 
	
	
</struts-config>

Quando aciono o botão para deletar ele não chama o método DELETE. Aguardo ajuda dos colegas.

Criado 6 de novembro de 2006
Ultima resposta 8 de nov. de 2006
Respostas 4
Participantes 4