user3268379 user3268379 - 17 days ago 5
SQL Question

Java sql delete row

Hello I am trying to delete a row from my database. I am getting no errors but it is doing nothing, any help or advice would be great!

public static void DeleteRow(String name)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);

PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
}
catch(Exception e)
{
System.out.println(e);
}
}

Answer

I guess name is a varchar type in DB so do like this

PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = '" + name + "';");

enclose name within single quotes '

Also this is not the way you are using is not the proper way of using Preparedstatement

Us the following way

PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate(); 

your full code after Proper PreparedStatement

public static void DeleteRow(String name)
  {
 try 
 {  
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate(); 

 }
 catch(Exception e)
 {
     System.out.println(e);
 }
}
Comments