1

How to delete a MySQL database selected record (row) I use this code

connectDB();
try{
    java.sql.PreparedStatement stmt = con.prepareStatement("DELETE FROM tbl_codes WHERE No=? ");
    String sql = "Delete FROM user WHERE No= "+txt_search_code.getText(); 
    pstmt = con.prepareStatement(sql);
    pstmt.setString(1,txt_search_code.getText());
    pstmt.execute();
    JOptionPane.showMessageDialog(null, " Your new records Deleted Succsessfully!!");   
} catch(Exception e){
    JOptionPane.showMessageDialog(null,e);
}
closeDB();

but it get an error like this -

java.sql.SQLException:Parameter index out of range(1>number of parameters,which is 0)

So how can I fix this probleam....(Examples please) Thanks

2
  • 1
    Remove your String sql. You've already had stmt. Use it to execute query instead of pstmt Commented Sep 26, 2017 at 6:28
  • I tried this code [ string sql = "Delete FROM user WHERE No= '" + txt_search_code.getText()+ "'"; ] but it still get an error like this - "java.sql.SQLException:Parameter index out of range(1>number of parameters,which is 0)" So how can I fix this probleam....(Examples please) Thanks Commented Sep 27, 2017 at 7:18

2 Answers 2

2

Try this:

connectDB();
try{
    java.sql.PreparedStatement stmt = con.prepareStatement("DELETE FROM tbl_codes WHERE No=? ");
    stmt.setString(1,txt_search_code.getText());
    stmt.execute();
    JOptionPane.showMessageDialog(null, " Your new records Deleted Succsessfully!!");   
} catch(Exception e){
    JOptionPane.showMessageDialog(null,e);
}
closeDB();
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is you are not using quotation marks around the string you want to delete.

It should be the following:

string sql = "Delete FROM user WHERE No= '" + txt_search_code.getText()+ "'";

Sql is now tring to convert to numerics.

1 Comment

Excuse me, that is definitely better!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.