How should I delete a row using a java variable in SQL table?
I am trying to delete a record from table member
(with two columns, name
and year
) using what the user has input (variable newName
and newYear
). I want to find the row that has the same record as what the user has input (name = newName && year=newYear)
and delete it. However, this code doesn’t change anything on the table (no row is deleted although what I have input is correct). What’s wrong with my code?
String newName = memName.getText(); int newYear = parseInt(memYear.getText());
are the variables used in the code below.
try { s = c.createStatement(); t = "DELETE FROM member " + "WHERE (name='" + newName + "'&& year='" + newYear + "')"; s.executeUpdate(t); s.close(); c.commit(); c.close(); } catch (SQLException ex) { Logger.getLogger(AddMember.class.getName()).log(Level.SEVERE, null, ex); } JOptionPane.showMessageDialog(null, "Saved."); memName.setText(null); memYear.setText(null);
I want the row with the info the user input to be deleted from the table, but it didn’t make any changes to my table.
Advertisement
Answer
the problem you have is that in SQL you cannot use &&
instead use AND
as shown in the following code:
t = "DELETE FROM member " + "WHERE (name='" + newName + "' AND year='" + newYear + "')";