Question:
I'm trying to delete data from a table with Java but for some reason the code isn't working. Excerpt from the code below:
public void excluir(ModeloObjeto modelo) throws Exception{
Connection conexao = CriaConexao.getConexao();
PreparedStatement ps;
ps = conexao.prepareCall("DELETE FROM `funcionalidade_celular` WHERE `nome_cel` LIKE ?");
ps.setString(1, "'"+modelo.getModelo()+"'");
executar(ps);
}
All other functionality is normal using the same logic, but the deletion only is not working. I've already printed the result of modelo.getModelo()
and did the test with the result of the output in the Workbench and it worked perfectly, but when deleting it from the web page it doesn't delete.
executar
method:
public void executar(PreparedStatement ps) throws Exception{
if(ps == null){
throw new NullPointerException();
}
try {
ps.execute();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
finally{
ps.close();
}
}
Metodo getConexao()
:
public static Connection getConexao(){
if(conexao == null){
try {
Class.forName("com.mysql.jdbc.Driver");
conexao = DriverManager.getConnection(URL,USER,PASS);
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(CriaConexao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conexao;
}
Answer:
Remove the backquotes from the table and column name and also the quotation marks surrounding the parameter passing in ps.setString()
Your code looks like this:
public void excluir(ModeloObjeto modelo) throws Exception{
Connection conexao = CriaConexao.getConexao();
PreparedStatement ps;
ps = conexao.prepareCall("DELETE FROM funcionalidade_celular WHERE nome_cel LIKE ?");
ps.setString(1, modelo.getModelo());
executar(ps);
}