0

I am trying to delete a record from a database using the following code in Java

try {
    Statement st = db.con.createStatement();
    con.stmt = st.executeUpdate("DELETE FROM item, WHERE Name=" + textField_name.getText());

however "stmt", (which is my PreparedStatement initialized in my connection class), is underlined and the code doesn't compile.

2 Answers 2

4

That's because executeUpdate returns an int, and presumably con.stmt isn't an int variable.

You shouldn't write your SQL that way in the first place though (it's invalid anyway due to the comma after item) - you should use a prepared statement:

PreparedStatement st = db.con.prepareStatement("DELETE FROM item WHERE Name=?");
st.setString(1, textField_name.getText());
int rowsDeleted = st.executeUpdate();

That way you don't open yourself up to SQL injection attacks.

Sign up to request clarification or add additional context in comments.

9 Comments

Like I said I have initialized my PreparedStatement in my connection class... I don't really understand what the second line is doing do you mind just explaining please as I am new to java.
@FatmaTurk: That's not the way prepared statements work though. You prepare the statement with the SQL, then set the parameters. It's not clear how you've prepared the statement before the code you've shown us, but the code you've shown definitely won't work, whereas the code I've shown should.
I am still getting the following error [java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0)]
@Jon Skeet, he is using a Statement and not a PreparedStatement class, so therefore, his st.executeUpdate(......) would work, BAD practice, but it works, it's basically executing a regular SQL statement. But the comma after item is an issue, but that would not cause a compiler error, more of a runtime error.
@Churk: No, it wouldn't work - because (as I said in the very first sentence) he's trying to assign the result to con.stmt. That's what's causing the compiler error.
|
1

st.executeUpdate() returns an int.

I think you wanted to execute con.stmt.executeUpdate()

1 Comment

now I understand why it was asking me to change "stmt" to "int"

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.