Java sql delete row

user3268379 picture user3268379 · Feb 4, 2014 · Viewed 57.4k times · Source

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

SpringLearner picture SpringLearner · Feb 4, 2014

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);
    }
}