Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 551
user3268379 Avatar asked Feb 04 '14 04:02

user3268379


People also ask

How do I manually delete a row in SQL?

To delete a row or rowsSelect the box to the left of the row or rows you want to delete in the Results pane. Press DELETE. In the message box asking for confirmation, click Yes.

How do you delete a record in Java?

Deleting a row can be straightforward: Just use deleteRow method of the ResultSet: rs. deleteRow( );


3 Answers

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);
    }
}
like image 137
SpringLearner Avatar answered Sep 22 '22 19:09

SpringLearner


You should never create a SQL statement in Java with String concatenation, it will be vulnerable to sql injection. Please do it this way.

String selectSQL = "DELETE FROM Table WHERE name = ?";
connection.prepareStatement(selectSQL);
preparedStatement.setString(1, name);
like image 37
jeremyjjbrown Avatar answered Sep 25 '22 19:09

jeremyjjbrown


          Class.forName("oracle.jdbc.driver.OracleDriver");
          Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "MANASH_APPN","MANASH");
          PreparedStatement ps = con.prepareStatement("delete from EMP21 where empid = ?");
           ps.setInt(1,90);
           ps.executeUpdate();
          con.commit();
          System.out.println("Records Delete Successfully....");
         con.close();
like image 30
Manash Ranjan Dakua Avatar answered Sep 26 '22 19:09

Manash Ranjan Dakua